File size: 30,880 Bytes
6da8440
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
292dc80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e5d809c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
"""One converter per Hugging Face dataset -> chat examples.

Every converter yields lists of chat messages (system/user/assistant[/tool]).
Data is read from the Hub's auto-converted Parquet files (refs/convert/parquet),
so every dataset loads the same way no matter how it was uploaded.
"""

from __future__ import annotations

import json
import random
import re
from collections import Counter
from typing import Iterator

from .common import SYSTEM_PROMPT, chat, est_tokens, pretty_name, strip_think
from . import minecraft, procedural

MAX_TOKENS = 3900  # leave room under the 4096 training context

# --------------------------------------------------------------- hub access
_hf_cache: dict = {}


def parquet_files(repo: str, config: str, split: str) -> list[str]:
    from huggingface_hub import HfApi

    key = repo
    if key not in _hf_cache:
        _hf_cache[key] = HfApi().list_repo_files(repo, repo_type="dataset", revision="refs/convert/parquet")
    prefix = f"{config}/{split}/"
    files = sorted(f for f in _hf_cache[key] if f.startswith(prefix) and f.endswith(".parquet"))
    if not files:  # older layout: config/<repo>-<split>.parquet
        files = sorted(f for f in _hf_cache[key] if f.startswith(f"{config}/") and f"-{split}" in f and f.endswith(".parquet"))
    if not files:
        raise FileNotFoundError(f"no parquet for {repo} {config}/{split}")
    return files


def iter_rows(repo: str, config: str = "default", split: str = "train", columns=None,
              batch_size: int = 128) -> Iterator[dict]:
    import pyarrow.parquet as pq
    from huggingface_hub import hf_hub_download

    for f in parquet_files(repo, config, split):
        path = hf_hub_download(repo, f, repo_type="dataset", revision="refs/convert/parquet")
        pf = pq.ParquetFile(path)
        cols = [c for c in columns if c in pf.schema_arrow.names] if columns else None
        for batch in pf.iter_batches(batch_size=batch_size, columns=cols):
            yield from batch.to_pylist()


def load_table(repo: str, config: str = "default", split: str = "train", columns=None):
    import pyarrow as pa
    import pyarrow.parquet as pq
    from huggingface_hub import hf_hub_download

    tables = []
    for f in parquet_files(repo, config, split):
        path = hf_hub_download(repo, f, repo_type="dataset", revision="refs/convert/parquet")
        tables.append(pq.read_table(path, columns=columns))
    return pa.concat_tables(tables)


def _fits(msgs, limit: int = MAX_TOKENS) -> bool:
    return est_tokens(msgs) <= limit


BUILD_LIMIT = 3500  # builds are number-heavy; keep a margin under the 4096 context


def _code_block(text: str, lang: str = "lua") -> str:
    t = (text or "").strip()
    if "```" in t:
        return t
    return f"```{lang}\n{t}\n```"


def _trim(text: str, limit: int) -> str:
    text = (text or "").strip()
    if len(text) <= limit:
        return text
    cut = text[:limit]
    p = cut.rfind("\n\n")
    return (cut[:p] if p > limit * 0.6 else cut).rstrip() + "\n..."


# --------------------------------------------------------------- building
def minecraft_builds(target: int, rng: random.Random, log, max_parts: int = 100):
    """mattismegevand/minecraft_builds: one row per block, grouped by structure."""
    tbl = load_table("mattismegevand/minecraft_builds", columns=["x", "y", "z", "mat", "structure"])
    df = tbl.to_pandas()
    df["structure"] = df["structure"].astype("category")
    df["mat"] = df["mat"].astype("category")
    counts = df["structure"].value_counts()
    cands = [s for s, c in counts.items() if 25 <= c <= 9000]
    log(f"  {len(counts)} structures, {len(cands)} in size range")
    rng.shuffle(cands)
    groups = df.groupby("structure", observed=True).indices
    xs, ys, zs, mats = df["x"].to_numpy(), df["y"].to_numpy(), df["z"].to_numpy(), df["mat"].astype(str).to_numpy()
    reasons: Counter = Counter()
    accepted = []
    for s in cands:
        if len(accepted) >= target:
            break
        idx = groups[s]
        blocks = [(int(xs[i]), int(ys[i]), int(zs[i]), mats[i]) for i in idx]
        ex, why = minecraft.make_example(str(s), blocks, rng, max_parts)
        if ex is None:
            reasons[str(why)] += 1
            continue
        msgs = chat(*ex)
        if not _fits(msgs, BUILD_LIMIT):
            reasons["too many tokens"] += 1
            continue
        accepted.append((str(s), blocks))
        yield msgs
    log(f"  accepted {len(accepted)}; rejected: {dict(reasons.most_common(6))}")
    # top up with rotated copies (same build facing another way) if short: up to 2 per build
    made = len(accepted)
    for rot_pass in (0, 1):
        for s, blocks in accepted:
            if made >= target:
                return
            rot = [1, 3][rot_pass] if rng.random() < 0.5 else [3, 2][rot_pass]
            ex, _ = minecraft.make_example(s, blocks, rng, max_parts, rotate=rot)
            if ex and _fits(chat(*ex), BUILD_LIMIT):
                made += 1
                yield chat(*ex)


BLOCK_RE = re.compile(r"\(\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*['\"]?([\w:. ]+?)['\"]?\s*\)")
DESC_PREFIX = re.compile(r"^(the|this) (image|picture|screenshot|render)( (shows|depicts|features|displays|is of))?\s*", re.I)


def minecraftbuildings(target: int, rng: random.Random, log, max_parts: int = 100):
    """assskelad/minecraftbuildings: Description + '(x, y, z, id)' tuples (legacy ids)."""
    rows = list(iter_rows("assskelad/minecraftbuildings", columns=["Description", "Block Info"], batch_size=32))
    rng.shuffle(rows)
    reasons: Counter = Counter()
    n = 0
    for r in rows:
        if n >= target:
            break
        raw = r.get("Block Info") or ""
        blocks = []
        for m in BLOCK_RE.finditer(raw):
            name = minecraft.legacy_name(m.group(4))
            if name:
                blocks.append((int(m.group(1)), int(m.group(2)), int(m.group(3)), name))
        if len(blocks) < 25 or len(blocks) > 12000:
            reasons["size"] += 1
            continue
        desc = DESC_PREFIX.sub("", (r.get("Description") or "").strip())
        desc = re.split(r"(?<=[.!?])\s", desc)
        desc = " ".join(desc[:3])[:500].strip()
        if len(desc) < 20:
            reasons["no desc"] += 1
            continue
        user = rng.choice(["Build this in Roblox: ", "Recreate this build with parts: ", "Build: "]) + desc[:1].lower() + desc[1:]
        ex, why = minecraft.make_example("minecraft build", blocks, rng, max_parts, desc=user)
        if ex is None:
            reasons[str(why)] += 1
            continue
        u, a = ex
        a = a.replace("minecraft build", "build").replace("Minecraft build", "Build")
        msgs = chat(u, a)
        if _fits(msgs, BUILD_LIMIT):
            n += 1
            yield msgs
    log(f"  rejected: {dict(reasons.most_common(6))}")


def procedural_builds(target: int, rng: random.Random, log):
    kinds: Counter = Counter()
    for kind, (u, a) in procedural.generate(target, seed=rng.randint(0, 10**9)):
        kinds[kind] += 1
        yield chat(u, a)
    log(f"  kinds: {dict(kinds)}")


def _strip_py_comments(code: str) -> str:
    out = []
    for line in code.splitlines():
        s = line.strip()
        if not s or s.startswith("#"):
            continue
        out.append(line.rstrip())
    return "\n".join(out)


def blender_3dcode(target: int, rng: random.Random, log, max_chars: int = 10000):
    rows = []
    total = 0
    for r in iter_rows("YipengGao/3DCode", config="3DCodeData",
                       columns=["caption_object", "caption_create_3D_object", "code"], batch_size=64):
        total += 1
        code = _strip_py_comments(r.get("code") or "")
        if 300 < len(code) <= max_chars:
            rows.append((r, code))
    log(f"  {len(rows)}/{total} scripts short enough (<= {max_chars} chars)")
    rng.shuffle(rows)
    for r, code in rows[:target]:
        what = (r.get("caption_object") or "").strip()
        user = r.get("caption_create_3D_object") or f"Write Blender Python code that creates {what}"
        intro = "Here's a Blender (bpy) script that builds it procedurally. Run it in Blender's Scripting tab; you can export the mesh as .fbx and import it into Roblox Studio."
        msgs = chat(user, f"{intro}\n\n```python\n{code}\n```")
        if _fits(msgs):
            yield msgs


def cadquery_code(target: int, rng: random.Random, log):
    rows = list(iter_rows("ThomasTheMaker/TextToCadQuery-2", columns=["input", "output"], batch_size=512))
    rng.shuffle(rows)
    n = 0
    for r in rows:
        if n >= target:
            break
        inp, out = (r.get("input") or "").strip(), (r.get("output") or "").strip()
        if len(inp) < 40 or "cadquery" not in out.lower() or len(inp) + len(out) > 7000:
            continue
        msgs = chat(f"{inp}\n\nWrite it as a CadQuery (Python) script.", _code_block(out, "python"))
        n += 1
        yield msgs


def cadquery_plans(target: int, rng: random.Random, log):
    rows = []
    for r in iter_rows("ThomasTheMaker/TextToCadQuery-1", columns=["description", "expert", "intermediate"], batch_size=512):
        if r.get("description") and r.get("expert") and 300 < len(r["expert"]) < 3500:
            rows.append(r)
        if len(rows) > target * 6:
            break
    rng.shuffle(rows)
    for r in rows[:target]:
        user = rng.choice(["Plan how to model this part step by step, with exact dimensions: ",
                           "Give me precise build steps for: ", "Break this shape into exact modeling steps: "]) + r["description"].strip()
        yield chat(user, r["expert"].strip())


def omar_cadquery(target: int, rng: random.Random, log):
    rows = list(iter_rows("OmarK211/text-to-cadquery-v1", columns=["messages"]))
    rng.shuffle(rows)
    n = 0
    for r in rows:
        if n >= target:
            break
        msgs = [m for m in (r.get("messages") or []) if m.get("role") in ("user", "assistant") and m.get("content")]
        if len(msgs) < 2 or msgs[0]["role"] != "user":
            continue
        out = [{"role": "system", "content": SYSTEM_PROMPT}] + [{"role": m["role"], "content": m["content"]} for m in msgs[:2]]
        if _fits(out):
            n += 1
            yield out


# --------------------------------------------------------------- agent
AGENT_SYSTEM = SYSTEM_PROMPT + (
    "\n\nYou are connected to a live Roblox Studio session. Use the tools to inspect the place "
    "before changing it, make focused edits, and check your work."
)


def _parse_args(a):
    if isinstance(a, dict):
        return a
    try:
        v = json.loads(a or "{}")
        return v if isinstance(v, dict) else {"value": v}
    except Exception:
        return {"input": str(a)}


def _tools_from_system(text: str) -> list[dict]:
    for block in re.findall(r"```(?:json)?\s*(.*?)```", text or "", re.DOTALL):
        try:
            data = json.loads(block)
        except Exception:
            continue
        items = data if isinstance(data, list) else data.get("tools", []) if isinstance(data, dict) else []
        tools = []
        for t in items:
            if not isinstance(t, dict):
                continue
            fn = t.get("function", t)
            if "name" in fn:
                tools.append({"type": "function", "function": {
                    "name": fn["name"], "description": (fn.get("description") or "")[:300],
                    "parameters": fn.get("parameters") or fn.get("input_schema") or {"type": "object", "properties": {}}}})
        if tools:
            return tools
    return []


def _agent_example(traj, tool_limit: int):
    msgs = [{"role": "system", "content": AGENT_SYSTEM}]
    tools: list[dict] = []
    used: dict[str, set] = {}
    for m in traj:
        if isinstance(m, str):
            try:
                m = json.loads(m)
            except Exception:
                return None, None
        role = m.get("role")
        if role == "system":
            tools = _tools_from_system(m.get("content") or "")
        elif role == "user":
            msgs.append({"role": "user", "content": (m.get("content") or "").strip()})
        elif role == "assistant":
            out = {"role": "assistant", "content": strip_think(m.get("content") or "")}
            calls = []
            for tc in m.get("tool_calls") or []:
                fn = tc.get("function") or {}
                name = fn.get("name")
                if not name:
                    continue
                args = _parse_args(fn.get("arguments"))
                used.setdefault(name, set()).update(args)
                calls.append({"id": tc.get("id") or f"call_{len(msgs)}", "type": "function",
                              "function": {"name": name, "arguments": args}})
            if calls:
                out["tool_calls"] = calls
            if out["content"] or calls:
                msgs.append(out)
        elif role == "tool":
            c = m.get("content")
            c = c if isinstance(c, str) else json.dumps(c, ensure_ascii=False)
            if len(c) > tool_limit:
                c = c[:tool_limit] + "...(truncated)"
            msgs.append({"role": "tool", "tool_call_id": m.get("tool_call_id"), "name": m.get("name"), "content": c})
    if not tools:
        tools = [{"type": "function", "function": {
            "name": n, "description": f"Roblox Studio tool: {n.replace('_', ' ')}",
            "parameters": {"type": "object", "properties": {k: {"type": "string"} for k in sorted(ks)}}}}
            for n, ks in used.items()]
    else:
        tools = [t for t in tools if t["function"]["name"] in used] or tools
    return msgs, tools


def roblox_agent(repo: str, target: int, rng: random.Random, log):
    status: Counter = Counter()
    kept = prefixes = 0
    rows = []
    for r in iter_rows(repo, columns=["trajectory", "exit_status", "category"], batch_size=16):
        st = str(r.get("exit_status") or "none").lower()
        status[st] += 1
        if any(bad in st for bad in ("error", "fail", "timeout", "max", "limit", "abort", "crash")):
            continue
        rows.append(r)
    log(f"  exit_status: {dict(status.most_common(8))}")
    rng.shuffle(rows)
    for r in rows:
        if kept >= target:
            break
        for limit in (1200, 500, 200):
            msgs, tools = _agent_example(r.get("trajectory") or [], limit)
            if not msgs or not any(m.get("tool_calls") for m in msgs):
                break
            if msgs[-1]["role"] == "tool":  # end on the model, not on a tool result
                msgs.append({"role": "assistant", "content": "Done."})
            tool_tok = len(json.dumps(tools)) // 3
            if est_tokens(msgs) + tool_tok <= MAX_TOKENS:
                kept += 1
                yield {"messages": msgs, "tools": tools}
                break
            if limit == 200:  # still too long: keep the longest prefix that fits
                for cut in range(len(msgs) - 1, 2, -1):
                    pre = msgs[:cut]
                    if pre[-1]["role"] != "assistant" or not pre[-1].get("content"):
                        continue
                    if any(m.get("tool_calls") for m in pre) and est_tokens(pre) + tool_tok <= MAX_TOKENS:
                        kept += 1
                        prefixes += 1
                        yield {"messages": pre, "tools": tools}
                        break
    log(f"  kept {kept} ({prefixes} cut to a prefix that fits)")


# --------------------------------------------------------------- luau
def _first_turns(pairs: list[dict], max_pairs: int = 2):
    for k in range(min(max_pairs, len(pairs) // 2), 0, -1):
        msgs = [{"role": "system", "content": SYSTEM_PROMPT}] + pairs[: 2 * k]
        if _fits(msgs):
            return msgs
    return None


def luau_coder(target: int, rng: random.Random, log):
    rows = list(iter_rows("khtsly/Luau-Coder-1.0-Preview-SFT", columns=["conversations"], batch_size=64))
    rng.shuffle(rows)
    n = 0
    for r in rows:
        if n >= target:
            break
        conv = [{"role": m["role"], "content": strip_think(m.get("content") or "")}
                for m in (r.get("conversations") or []) if m.get("role") in ("user", "assistant")]
        if len(conv) < 2 or conv[0]["role"] != "user" or not all(m["content"] for m in conv[:2]):
            continue
        msgs = _first_turns(conv)
        if msgs:
            n += 1
            yield msgs


def luaudev(target: int, rng: random.Random, log):
    roles = {"human": "user", "user": "user", "gpt": "assistant", "assistant": "assistant"}
    picked = []
    for r in iter_rows("Pinkstack/LuauDev-instructions-SFT-full", columns=["conversations"], batch_size=32):
        picked.append(r)
        if len(picked) >= target * 4:
            break
    rng.shuffle(picked)
    n = 0
    for r in picked:
        if n >= target:
            break
        conv = [{"role": roles[m["from"]], "content": strip_think(m.get("value") or "")}
                for m in (r.get("conversations") or []) if m.get("from") in roles]
        if len(conv) < 2 or conv[0]["role"] != "user":
            continue
        msgs = _first_turns(conv, 1)
        if msgs:
            n += 1
            yield msgs


def luau_reasoning(target: int, rng: random.Random, log):
    rows = list(iter_rows("TorpedoSoftware/Roblox-Luau-Reasoning-v1.0", columns=["prompt", "code", "explanation"]))
    rng.shuffle(rows)
    n = 0
    for r in rows:
        if n >= target:
            break
        if not r.get("prompt") or not r.get("code"):
            continue
        a = _code_block(r["code"]) + "\n\n" + _trim(r.get("explanation") or "", 700)
        msgs = chat(r["prompt"], a)
        if _fits(msgs):
            n += 1
            yield msgs


def instruction_rows(repo: str, target: int, rng: random.Random, log, split: str = "train"):
    rows = list(iter_rows(repo, split=split, columns=["instruction", "input", "output"]))
    rng.shuffle(rows)
    n = 0
    for r in rows:
        if n >= target:
            break
        ins, inp, out = (r.get("instruction") or "").strip(), (r.get("input") or "").strip(), (r.get("output") or "").strip()
        if not ins or len(out) < 20:
            continue
        user = ins + (f"\n\n{inp}" if inp else "")
        looks_code = bool(re.search(r"\b(local|function|end|Instance\.new|game:GetService)\b", out))
        a = _code_block(out) if looks_code and "```" not in out else out
        msgs = chat(user, a)
        if _fits(msgs):
            n += 1
            yield msgs


def luau_corpus(target: int, rng: random.Random, log):
    rows = list(iter_rows("Roblox/luau_corpus", columns=["prompt", "completion"]))
    rng.shuffle(rows)
    n = 0
    for r in rows:
        if n >= target:
            break
        p, c = (r.get("prompt") or "").strip("\n"), (r.get("completion") or "").strip("\n")
        if len(p) < 80 or len(c) < 80 or len(p) + len(c) > 6000:
            continue
        msgs = chat(f"Continue this Roblox Luau code:\n\n```lua\n{p}\n```", f"```lua\n{c}\n```")
        n += 1
        yield msgs


# --------------------------------------------------------------- knowledge
def docs_rows(repo: str, target: int, rng: random.Random, log, config="default", title_col="title"):
    cols = ["title", "url", "content"] if title_col == "title" else ["url", "content"]
    rows = list(iter_rows(repo, config=config, columns=cols, batch_size=64))
    rng.shuffle(rows)
    n = 0
    for r in rows:
        if n >= target:
            break
        content = (r.get("content") or "").strip()
        title = (r.get("title") or "").strip()
        if not title:
            url = (r.get("url") or "").rstrip("/")
            title = pretty_name(url.rsplit("/", 1)[-1].split(".")[0]) if url else ""
        if len(content) < 300 or not title:
            continue
        q = rng.choice(["Explain {t} in Roblox.", "What is {t}?", "How does {t} work in Roblox?", "Tell me about {t}."]).format(t=title)
        msgs = chat(q, _trim(content, 2600))
        if _fits(msgs):
            n += 1
            yield msgs


def devforum(target: int, rng: random.Random, log):
    rows = list(iter_rows("khtsly/devforum-roblox-text", config="all", columns=["title", "content", "category"], batch_size=64))
    rng.shuffle(rows)
    n = 0
    for r in rows:
        if n >= target:
            break
        content, title = (r.get("content") or "").strip(), (r.get("title") or "").strip()
        if len(content) < 300 or not title:
            continue
        msgs = chat(f"From the Roblox DevForum: {title}. What does it say?", _trim(content, 2600))
        if _fits(msgs):
            n += 1
            yield msgs


# --------------------------------------------------------------- eval
def robloxqa_eval(rng: random.Random, limit: int = 1000):
    rows = list(iter_rows("TorpedoSoftware/RobloxQA-v2.0", split="test"))
    rng.shuffle(rows)
    for r in rows[:limit]:
        choices = [r["answer"], r["incorrect_0"], r["incorrect_1"], r["incorrect_2"]]
        order = list(range(4))
        rng.shuffle(order)
        yield {"question": r["question"], "choices": [choices[i] for i in order], "answer": order.index(0)}


# --------------------------------------------------------------- Radin's own repo
BLOXY_TRAINING_ZIP = "https://github.com/Radin-dev1/BloxyAItraining/raw/main/Ropilot-Studio-training-data-inspection.zip"
SKILL_QUESTIONS = {
    "Anti-Patterns": ["What should I avoid when {topic}?", "What are the common mistakes when {topic}?"],
    "Limitations": ["What are the Studio MCP limits and workarounds when {topic}?"],
    "Build Process": ["Walk me through the process for {topic}.", "What steps do you follow when {topic}?"],
    "Verification": ["How do you check your work after {topic}?"],
    "Folder": ["How should I organize folders when {topic}?"],
    "Quick Reference": ["Give me a quick reference for {topic}.", "What are the key rules for {topic}?"],
    "Checklist": ["Give me a review checklist for {topic}."],
    "Domain Knowledge": ["What Roblox details matter when {topic}?"],
    "Design Brief": ["What should a design brief include before {topic}?"],
}
SKILL_TOPICS = {
    "building-3d-objects": "building a single object or prop in Roblox Studio",
    "building-maps": "building a whole map in Roblox Studio",
    "roblox-best-practices": "writing Luau for a Roblox game",
    "roblox-building": "building geometry and props with Luau",
    "roblox-design-consultant": "designing a build from a vague request",
    "roblox-game-design": "designing a Roblox game's core loop",
    "roblox-luau-core": "writing Luau",
    "roblox-studio-mcp": "working in Roblox Studio through MCP",
}


def bloxy_skill_guides(target: int, rng: random.Random, log):
    """Roblox skill guides from Radin-dev1/BloxyAItraining, split into Q&A by section.

    The SuperbulletAI zip in that repo is deliberately NOT used: it is code extracted
    from a proprietary app with no redistribution license.
    """
    import io
    import urllib.request
    import zipfile

    raw = urllib.request.urlopen(BLOXY_TRAINING_ZIP, timeout=60).read()
    zf = zipfile.ZipFile(io.BytesIO(raw))
    out = []
    for name in zf.namelist():
        if not name.endswith("SKILL.md"):
            continue
        skill = name.rstrip("/").split("/")[-2]
        topic = SKILL_TOPICS.get(skill, skill.replace("-", " "))
        text = zf.read(name).decode("utf-8", "replace")
        text = re.sub(r"^---.*?---\s*", "", text, flags=re.DOTALL)  # drop frontmatter
        text = re.sub(r"\*\*AUTHORITY\*\*:.*?\n", "", text)
        sections = re.split(r"\n(?=## )", text)
        for sec in sections[1:]:
            head, _, body = sec.partition("\n")
            head = head.lstrip("# ").strip()
            body = body.strip()
            if len(body) < 200 or re.search(r"When to Load|Supplementary|Reference Routing|Session", head):
                continue
            qs = next((v for k, v in SKILL_QUESTIONS.items() if k.lower() in head.lower()), [])
            qs = qs + [f"Explain '{head}' for {{topic}}.", f"I'm {{topic}}. What do I need to know about {head.lower()}?"]
            for q in qs[:3]:
                msgs = chat(q.format(topic=topic), _trim(body, 4500))
                if _fits(msgs):
                    out.append(msgs)
    log(f"  {len(out)} Q&A pairs from the skill guides")
    rng.shuffle(out)
    yield from out[:target]


# --------------------------------------------------------------- Hack337 curated schematics
def hack337_schematics(target: int, rng: random.Random, log, max_parts: int = 100):
    """Hack337/Minecraft-Schematics (MIT): 669 curated builds as JSON grids
    (layers[y][z][x] chars + palette) with an English request per build.
    Converted to Roblox Parts; rotated copies top up the count."""
    from huggingface_hub import snapshot_download

    root = snapshot_download("Hack337/Minecraft-Schematics", repo_type="dataset",
                             allow_patterns=["blueprints/*.json", "blueprints_mapping.jsonl"])
    names = {}
    with open(f"{root}/blueprints_mapping.jsonl", encoding="utf-8") as f:
        for line in f:
            try:
                r = json.loads(line)
            except Exception:
                continue
            if r.get("filename") and r.get("short_name_en"):
                names[r["filename"]] = r["short_name_en"].strip()
    builds = []
    for fn, req in names.items():
        try:
            bp = json.load(open(f"{root}/blueprints/{fn}", encoding="utf-8"))
        except Exception:
            continue
        pal = bp.get("palette") or {}
        blocks = []
        for y, layer in enumerate(bp.get("layers") or []):
            for z, row in enumerate(layer):
                for x, ch in enumerate(row):
                    if ch != "." and ch in pal:
                        blocks.append((x, y, z, pal[ch]))
        if 20 <= len(blocks) <= 12000:
            builds.append((req, blocks))
    log(f"  {len(builds)} usable builds of {len(names)}")
    rng.shuffle(builds)
    reasons: Counter = Counter()
    made = 0
    for rot in (0, 1, 2, 3):  # original first, then rotated copies if more are needed
        for req, blocks in builds:
            if made >= target:
                log(f"  rejected: {dict(reasons.most_common(5))}")
                return
            thing = re.sub(r"^(please\s+)?(build|make|create)\s+(me\s+)?", "", req, flags=re.I).strip() or "build"
            user = req[:1].upper() + req[1:] if rot == 0 else rng.choice(
                [f"Build {thing}.", f"make {thing}", f"Can you build {thing} in Roblox?", f"Create {thing} out of parts."])
            ex, why = minecraft.make_example(thing, blocks, rng, max_parts, rotate=rot, desc=user)
            if ex is None:
                reasons[str(why)] += 1
                continue
            msgs = chat(*ex)
            if not _fits(msgs, BUILD_LIMIT):
                reasons["too many tokens"] += 1
                continue
            made += 1
            yield msgs
    log(f"  rejected: {dict(reasons.most_common(5))}")


# --------------------------------------------------------------- text -> brick builds
BRICK_RE = re.compile(r"(\d+)x(\d+)\s*\((\d+),\s*(\d+),\s*(\d+)\)")
BRICK_UNIT, BRICK_LAYER = 2.0, 2.4  # studs per brick stud / per brick layer (toy brick ratio)
CAPTION_STYLE = [  # (keywords, material, colors)
    (("wood", "wooden", "oak", "timber"), "WoodPlanks", ["b8945f", "7a5a34", "4f3218"]),
    (("metal", "steel", "iron", "chrome", "aluminum"), "Metal", ["8e8e86", "6e7378", "c8c8c8"]),
    (("glass", "transparent"), "Glass", ["c0e4ec"]),
    (("stone", "concrete", "brick"), "Concrete", ["a3a2a5", "8a8478"]),
    (("red",), "SmoothPlastic", ["c4281c"]), (("blue",), "SmoothPlastic", ["0d69ac"]),
    (("green",), "SmoothPlastic", ["4b974b"]), (("yellow",), "SmoothPlastic", ["f5cd30"]),
    (("black", "dark"), "SmoothPlastic", ["1b2a35"]), (("white",), "SmoothPlastic", ["f2f3f3"]),
]


def brick_builds(target: int, rng: random.Random, log, max_parts: int = 90):
    """AvaLovelace/StableText2Brick: caption -> physically stable brick structure.

    Bricks ('2x4 (x,y,z)', z = layer) are voxelized and greedy-merged into Parts,
    then written in the same P(...) build format as every other Bloxy build.
    """
    from .luau_build import Build, Part, answer as build_answer
    from .common import pascal

    rows = list(iter_rows("AvaLovelace/StableText2Brick", columns=["captions", "bricks", "category_id"], batch_size=512))
    rng.shuffle(rows)
    seen_objects, n, reasons = set(), 0, Counter()
    for r in rows:
        if n >= target:
            break
        caps = [c for c in (r.get("captions") or []) if c and len(c) > 15]
        bricks = BRICK_RE.findall(r.get("bricks") or "")
        if not caps or len(bricks) < 4:
            reasons["empty"] += 1
            continue
        cells = set()
        for h, w, x, y, z in bricks:
            h, w, x, y, z = map(int, (h, w, x, y, z))
            for i in range(h):
                for j in range(w):
                    cells.add((x + i, z, y + j))  # (x, up, z) like Roblox
        boxes = list(minecraft.greedy_boxes(cells, "full"))
        if len(boxes) > max_parts:
            reasons["too many parts"] += 1
            continue
        cap = rng.choice(caps).strip().rstrip(".")
        low = cap.lower()
        mat, cols = "SmoothPlastic", ["a3a2a5", "c4281c", "0d69ac", "f5cd30", "4b974b"]
        for keys, m, cs in CAPTION_STYLE:
            if any(re.search(rf"\b{k}\b", low) for k in keys):
                mat, cols = m, cs
                break
        color = rng.choice(cols)
        xs = [c[0] for c in cells]; zs = [c[2] for c in cells]
        cx, cz = (min(xs) + max(xs) + 1) / 2, (min(zs) + max(zs) + 1) / 2
        name = " ".join(re.findall(r"[A-Za-z]+", low)[:4]) or "object"
        b = Build(pascal(name))
        for x0, y0, z0, dx, dy, dz in boxes:
            b.add(Part("Block", (dx * BRICK_UNIT, dy * BRICK_LAYER, dz * BRICK_UNIT),
                       ((x0 - cx + dx / 2) * BRICK_UNIT, (y0 + dy / 2) * BRICK_LAYER, (z0 - cz + dz / 2) * BRICK_UNIT),
                       mat, color, None, 0.4 if mat == "Glass" else 0.0))
        w, hgt, d = b.bounds()
        user = rng.choice(["Build {c}.", "build {c}", "Make {c} out of parts.", "Can you build {c}?",
                           "Create {c} in Roblox Studio."]).format(c=cap[:1].lower() + cap[1:])
        intro = f"Here it is: {len(boxes)} anchored parts, about {int(w)}x{int(d)} studs and {int(hgt)} studs tall, built layer by layer so every part rests on the one below."
        msgs = chat(user, build_answer(intro, b))
        if _fits(msgs, BUILD_LIMIT):
            n += 1
            yield msgs
    log(f"  rejected: {dict(reasons.most_common(4))}")