Datasets:
Packet A11 v1: 6021/1026, leakage 0
Browse files- README.md +58 -0
- data/test.jsonl +0 -0
- data/train.jsonl +0 -0
- tools/a11_score.py +121 -0
- tools/build_packet_a11.py +722 -0
- tools/check_a11.py +145 -0
- tools/packet_a11_build.log +10 -0
README.md
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
language:
|
| 4 |
+
- ar
|
| 5 |
+
- en
|
| 6 |
+
task_categories:
|
| 7 |
+
- text-generation
|
| 8 |
+
tags:
|
| 9 |
+
- code
|
| 10 |
+
- arabic
|
| 11 |
+
- python
|
| 12 |
+
- verifiable-rewards
|
| 13 |
+
- grpo
|
| 14 |
+
size_categories:
|
| 15 |
+
- 1K<n<10K
|
| 16 |
+
configs:
|
| 17 |
+
- config_name: default
|
| 18 |
+
data_files:
|
| 19 |
+
- split: train
|
| 20 |
+
path: data/train.jsonl
|
| 21 |
+
- split: test
|
| 22 |
+
path: data/test.jsonl
|
| 23 |
+
---
|
| 24 |
+
|
| 25 |
+
# Arabic Code Packet A11 (verifiable)
|
| 26 |
+
|
| 27 |
+
Arabic-instruction Python tasks where every answer is machine-checkable. Built by ABUZ8 LLC for the SUPERBRAIN-1 Arabic brain (https://huggingface.co/abuz8studios/SUPERBRAIN-1).
|
| 28 |
+
|
| 29 |
+
- **6,021 train / 1,026 test**, 27 deterministic template generators, seed 11.
|
| 30 |
+
- No LLM-generated content: every prompt, reference solution and test comes from code in `tools/build_packet_a11.py`.
|
| 31 |
+
|
| 32 |
+
| Kind | Train | Test | How it is graded |
|
| 33 |
+
|---|---|---|---|
|
| 34 |
+
| predict-the-output | 2,230 | 380 | exact match with the snippet's real stdout (executed in a subprocess at build time) |
|
| 35 |
+
| write-a-function | 2,453 | 418 | 5-8 hidden unit tests |
|
| 36 |
+
| fix-the-bug | 669 | 114 | hidden tests; buggy version verified to fail |
|
| 37 |
+
| complete-the-function | 669 | 114 | hidden tests |
|
| 38 |
+
|
| 39 |
+
## Verification (`tools/check_a11.py`, exit 0)
|
| 40 |
+
|
| 41 |
+
```
|
| 42 |
+
[counts] train=6021 exam=1026 generators train=27 exam=27 missing_fields=0 dup_prompts=0 -> OK
|
| 43 |
+
[reference] sample=400 pass=400/400 (100.00%) | fix_bug buggy versions passing=0/67 -> OK
|
| 44 |
+
[predict] sample=200 re-executed_match=200/200 -> OK
|
| 45 |
+
[negative] other-item completions scored correct: 0/100 -> OK
|
| 46 |
+
[leakage] train_vs_exam exact 0, norm 0, qnorm 0, qhash 0, code 0 -> LEAKAGE=0
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
Test items use a phrasing template never seen in train and parameter combinations disjoint from train.
|
| 50 |
+
|
| 51 |
+
## Fields
|
| 52 |
+
`task, src, kind, topic, template, prompt, completion, answer, qhash, lang`; predict items add `code`; code items add `entry, reference, tests, test_code` (fix-the-bug also `buggy`).
|
| 53 |
+
|
| 54 |
+
## Scoring
|
| 55 |
+
`python tools/a11_score.py ITEMS.jsonl PREDS.jsonl` - runs model code against hidden tests in a subprocess with a 5 s timeout (process isolation, not a security sandbox).
|
| 56 |
+
|
| 57 |
+
## Model scores
|
| 58 |
+
None yet. Baselines for SUPERBRAIN-1 will be added here once measured.
|
data/test.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/train.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tools/a11_score.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""a11_score.py - scorer for SUPERBRAIN Packet A11 (Arabic-instruction Python coding).
|
| 3 |
+
|
| 4 |
+
score(pred_text, item, timeout=5.0) -> bool
|
| 5 |
+
kind == "predict_output": the predicted output (last ``` block, else the text after the last
|
| 6 |
+
"الناتج:", else the whole text) must equal item["answer"] exactly, after normalising line
|
| 7 |
+
endings and trailing whitespace on each line (leading/trailing blank lines ignored).
|
| 8 |
+
kind in {"write_function", "fix_bug", "complete_function"}: the last ```python block (else the
|
| 9 |
+
whole text) is run in a fresh `python -I` subprocess followed by item["test_code"] (hidden
|
| 10 |
+
asserts); pass iff exit code 0 and the sentinel line is printed within `timeout` seconds.
|
| 11 |
+
|
| 12 |
+
CLI: python a11_score.py ITEMS.jsonl PREDS.jsonl
|
| 13 |
+
PREDS.jsonl is aligned line-by-line with ITEMS.jsonl; each line is {"pred": text} (or "output"/
|
| 14 |
+
"completion"), or a bare JSON string. Prints accuracy overall and by kind.
|
| 15 |
+
"""
|
| 16 |
+
import os, re, sys, json, subprocess, collections
|
| 17 |
+
|
| 18 |
+
try:
|
| 19 |
+
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
| 20 |
+
except Exception:
|
| 21 |
+
pass
|
| 22 |
+
|
| 23 |
+
SENTINEL = "__A11_TESTS_PASSED__"
|
| 24 |
+
CODE_KINDS = ("write_function", "fix_bug", "complete_function")
|
| 25 |
+
_FENCE_ANY = re.compile(r"```[^\n`]*\n(.*?)```", re.S)
|
| 26 |
+
_FENCE_PY = re.compile(r"```(?:python|py|python3)?[ \t]*\n(.*?)```", re.S | re.I)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def run_py(code, timeout=5.0, python=None):
|
| 30 |
+
"""Run `code` in a fresh isolated CPU-only interpreter. Returns (returncode, stdout, stderr)."""
|
| 31 |
+
env = dict(os.environ, CUDA_VISIBLE_DEVICES="", PYTHONIOENCODING="utf-8", PYTHONUTF8="1")
|
| 32 |
+
flags = 0x08000000 if os.name == "nt" else 0 # CREATE_NO_WINDOW
|
| 33 |
+
try:
|
| 34 |
+
p = subprocess.run([python or sys.executable, "-I", "-X", "utf8", "-"], input=code.encode("utf-8"),
|
| 35 |
+
capture_output=True, timeout=timeout, env=env, creationflags=flags)
|
| 36 |
+
except subprocess.TimeoutExpired:
|
| 37 |
+
return -9, "", "TIMEOUT"
|
| 38 |
+
out = p.stdout.decode("utf-8", "replace").replace("\r\n", "\n")
|
| 39 |
+
err = p.stderr.decode("utf-8", "replace").replace("\r\n", "\n")
|
| 40 |
+
return p.returncode, out, err
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def norm_out(s):
|
| 44 |
+
lines = (s or "").replace("\r\n", "\n").replace("\r", "\n").split("\n")
|
| 45 |
+
return "\n".join(l.rstrip() for l in lines).strip("\n").strip()
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def extract_output(text):
|
| 49 |
+
t = text or ""
|
| 50 |
+
blocks = _FENCE_ANY.findall(t)
|
| 51 |
+
if blocks:
|
| 52 |
+
return blocks[-1]
|
| 53 |
+
if "الناتج:" in t:
|
| 54 |
+
return t.rsplit("الناتج:", 1)[1]
|
| 55 |
+
return t
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def extract_code(text):
|
| 59 |
+
t = text or ""
|
| 60 |
+
blocks = _FENCE_PY.findall(t)
|
| 61 |
+
if blocks:
|
| 62 |
+
return blocks[-1]
|
| 63 |
+
blocks = _FENCE_ANY.findall(t)
|
| 64 |
+
if blocks:
|
| 65 |
+
return blocks[-1]
|
| 66 |
+
t = t.strip()
|
| 67 |
+
if t.startswith("الجواب:"):
|
| 68 |
+
t = t[len("الجواب:"):]
|
| 69 |
+
return t
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def program_with_tests(code, test_code):
|
| 73 |
+
return f"{code}\n\n{test_code}\nprint({SENTINEL!r})\n"
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def score(pred_text, item, timeout=5.0):
|
| 77 |
+
kind = item.get("kind")
|
| 78 |
+
if kind == "predict_output":
|
| 79 |
+
return norm_out(extract_output(pred_text)) == norm_out(item["answer"])
|
| 80 |
+
if kind in CODE_KINDS:
|
| 81 |
+
code = extract_code(pred_text)
|
| 82 |
+
if not code.strip():
|
| 83 |
+
return False
|
| 84 |
+
rc, out, _ = run_py(program_with_tests(code, item["test_code"]), timeout=timeout)
|
| 85 |
+
return rc == 0 and SENTINEL in out
|
| 86 |
+
raise ValueError(f"unknown kind {kind!r}")
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _pred_of(line):
|
| 90 |
+
v = json.loads(line)
|
| 91 |
+
if isinstance(v, str):
|
| 92 |
+
return v
|
| 93 |
+
for k in ("pred", "output", "completion", "text"):
|
| 94 |
+
if k in v:
|
| 95 |
+
return v[k]
|
| 96 |
+
return ""
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def main(argv):
|
| 100 |
+
if len(argv) != 3:
|
| 101 |
+
print(__doc__)
|
| 102 |
+
return 2
|
| 103 |
+
items = [json.loads(l) for l in open(argv[1], encoding="utf-8") if l.strip()]
|
| 104 |
+
preds = [_pred_of(l) for l in open(argv[2], encoding="utf-8") if l.strip()]
|
| 105 |
+
if len(items) != len(preds):
|
| 106 |
+
print(f"length mismatch items={len(items)} preds={len(preds)}")
|
| 107 |
+
return 2
|
| 108 |
+
tot, ok = collections.Counter(), collections.Counter()
|
| 109 |
+
for it, p in zip(items, preds):
|
| 110 |
+
k = it.get("kind")
|
| 111 |
+
tot[k] += 1
|
| 112 |
+
ok[k] += bool(score(p, it))
|
| 113 |
+
n, c = sum(tot.values()), sum(ok.values())
|
| 114 |
+
print(f"A11 accuracy {c}/{n} = {100 * c / max(n, 1):.2f}%")
|
| 115 |
+
for k in sorted(tot):
|
| 116 |
+
print(f" {k}: {ok[k]}/{tot[k]} = {100 * ok[k] / tot[k]:.2f}%")
|
| 117 |
+
return 0
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
if __name__ == "__main__":
|
| 121 |
+
sys.exit(main(sys.argv))
|
tools/build_packet_a11.py
ADDED
|
@@ -0,0 +1,722 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""build_packet_a11.py - SUPERBRAIN-1 Packet A11 (Arabic-instruction Python coding, train + exam).
|
| 3 |
+
|
| 4 |
+
Fully programmatic: every prompt, reference solution, hidden test and gold output is produced by
|
| 5 |
+
the templates in this file (random.Random(11)) and by EXECUTING code. No LLM text, no teacher outputs.
|
| 6 |
+
|
| 7 |
+
Kinds (27 generators):
|
| 8 |
+
predict_output (10) - "ما الذي يطبعه البرنامج؟" gold = stdout of the snippet, obtained by running
|
| 9 |
+
it in a fresh `python -I` subprocess (timeout) at build time.
|
| 10 |
+
write_function (11) - "اكتب دالة ..." hidden asserts; expected values computed from the
|
| 11 |
+
reference, then reference+asserts re-run in a subprocess and must pass.
|
| 12 |
+
fix_bug (3) - buggy function shown; reference must pass, buggy version must FAIL the tests.
|
| 13 |
+
complete_function (3) - skeleton with ____ to fill; reference must pass the tests.
|
| 14 |
+
|
| 15 |
+
Schema (A10-style): task, src, prompt (HEAD + question + "\\nالجواب:"), completion, answer, qhash
|
| 16 |
+
+ kind, topic, template, lang; predict: code; code kinds: entry, reference, tests, test_code (+ buggy).
|
| 17 |
+
|
| 18 |
+
Split: each generator has 3 phrasings; phrasings 0/1 -> train, phrasing 2 -> exam ONLY, and exam
|
| 19 |
+
parameter tuples are disjoint from all train parameter tuples of that generator.
|
| 20 |
+
Leakage check: exact / normalized prompt, normalized question, question hash, param combos,
|
| 21 |
+
snippet code and reference code overlap train<->exam.
|
| 22 |
+
Scoring: a11_score.py (exact output match, or hidden tests in a subprocess with 5 s timeout).
|
| 23 |
+
"""
|
| 24 |
+
import os, re, sys, json, copy, time, random, hashlib, collections
|
| 25 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 26 |
+
|
| 27 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = ""
|
| 28 |
+
try:
|
| 29 |
+
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
| 30 |
+
except Exception:
|
| 31 |
+
pass
|
| 32 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 33 |
+
from a11_score import run_py, program_with_tests, SENTINEL # noqa: E402
|
| 34 |
+
|
| 35 |
+
T = os.environ.get("A11_DIR", r"E:\ABU\02_PROJECTS\AHMAD-1\train")
|
| 36 |
+
OUT = os.environ.get("A11_OUT", "packet_a11")
|
| 37 |
+
SEED = 11
|
| 38 |
+
N_TRAIN_PER_GEN = int(os.environ.get("A11_NTRAIN", "223"))
|
| 39 |
+
N_EXAM_PER_GEN = int(os.environ.get("A11_NEXAM", "38"))
|
| 40 |
+
WORKERS = int(os.environ.get("A11_WORKERS", "6"))
|
| 41 |
+
BUILD_TIMEOUT = 10.0
|
| 42 |
+
HEAD = "المهمة: حل مهمة البرمجة التالية بلغة بايثون.\nسؤال: "
|
| 43 |
+
TAIL = "\nالجواب:"
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def ch(r, xs):
|
| 47 |
+
return xs[r.randrange(len(xs))]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
AR_NAMES = ["أحمد", "خالد", "يوسف", "عمر", "حسن", "سلمى", "زينب", "مريم", "ليلى", "فيصل",
|
| 51 |
+
"علي", "سعيد", "هدى", "نور", "باسل", "هشام", "رنا", "وليد", "منى", "راشد"]
|
| 52 |
+
AR_WORDS = ["كتاب", "مدرسة", "قلم", "سماء", "بحر", "شمس", "قمر", "نهر", "جبل", "وردة", "باب", "بيت",
|
| 53 |
+
"سيارة", "طائرة", "حاسوب", "برمجة", "مكتبة", "علم", "سلام", "مدينة", "شجرة", "طالب", "معلم",
|
| 54 |
+
"لغة", "عربية", "قهوة", "ماء", "نور", "حديقة", "صديق", "دفتر", "سوق", "عمل", "ليل", "نهار",
|
| 55 |
+
"فجر", "مطر", "رمل", "صحراء", "جمل", "حصان", "سفينة", "ميناء", "تفاحة", "برتقال", "خبز"]
|
| 56 |
+
AR_LETTERS = ["ا", "ب", "ت", "ر", "س", "ل", "م", "ن", "ه", "و", "ي", "ع", "ك", "د", "ق", "ح", "ج", "ف", "ص", "ش"]
|
| 57 |
+
EN_WORDS = ["python", "data", "brain", "code", "table", "apple", "river", "stone", "light", "music",
|
| 58 |
+
"garden", "planet", "window", "rocket", "matrix", "signal", "vector", "pixel", "cloud",
|
| 59 |
+
"engine", "banana", "orange", "summer", "winter", "falcon", "desert", "camel", "coffee"]
|
| 60 |
+
SHORT_EN = ["a", "an", "of", "to", "is", "in", "on", "at", "by", "we", "it", "go", "up"]
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def ar_sentence(r, lo=0, hi=7):
|
| 64 |
+
return " ".join(ch(r, AR_WORDS) for _ in range(r.randint(lo, hi)))
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def en_sentence(r, lo=0, hi=8):
|
| 68 |
+
pool = EN_WORDS + SHORT_EN
|
| 69 |
+
return " ".join(ch(r, pool) for _ in range(r.randint(lo, hi)))
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def ints(r, nlo, nhi, lo, hi):
|
| 73 |
+
return [r.randint(lo, hi) for _ in range(r.randint(nlo, nhi))]
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def body(*lines):
|
| 77 |
+
return "\n".join(lines)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
# ---------------------------------------------------------------- predict-the-output generators
|
| 81 |
+
# each returns dict(kind="predict_output", key, topic, code)
|
| 82 |
+
PQ = ["ما الذي يطبعه برنامج بايثون التالي؟\n```python\n{code}\n```",
|
| 83 |
+
"توقّع ناتج تنفيذ الشيفرة التالية واكتبه كما يظهر على الشاشة تمامًا:\n```python\n{code}\n```",
|
| 84 |
+
"نفّذ المقطع البرمجي الآتي في ذهنك، ثم اكتب بدقة كل ما سيُطبع سطرًا بسطر:\n```python\n{code}\n```"]
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def g_p_slice(r):
|
| 88 |
+
v = ch(r, ["a", "nums", "xs", "data", "lst", "items"])
|
| 89 |
+
a = ints(r, 5, 9, -9, 40)
|
| 90 |
+
i = r.randint(0, 3)
|
| 91 |
+
j = r.randint(i + 1, len(a))
|
| 92 |
+
s = ch(r, [-1, 2, 3, -2])
|
| 93 |
+
agg = ch(r, ["len", "sum", "max", "min"])
|
| 94 |
+
code = body(f"{v} = {a}", f"print({v}[{i}:{j}])", f"print({v}[::{s}])", f"print({agg}({v}[{i}:{j}]))")
|
| 95 |
+
return dict(kind="predict_output", key=(v, tuple(a), i, j, s, agg), topic="list_slicing", code=code)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def g_p_loop(r):
|
| 99 |
+
init, a = r.randint(0, 20), r.randint(-5, 10)
|
| 100 |
+
b, s, k = a + r.randint(3, 25), r.randint(1, 4), r.randint(1, 9)
|
| 101 |
+
op = ch(r, ["+=", "-="])
|
| 102 |
+
v, it = ch(r, ["total", "acc", "s", "result"]), ch(r, ["i", "n", "j", "x"])
|
| 103 |
+
code = body(f"{v} = {init}", f"for {it} in range({a}, {b}, {s}):", f" {v} {op} {it} * {k}",
|
| 104 |
+
f"print({v})", f"print({it})")
|
| 105 |
+
return dict(kind="predict_output", key=(init, a, b, s, k, op, v, it), topic="for_loop", code=code)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def g_p_str(r):
|
| 109 |
+
w = ch(r, EN_WORDS) + ch(r, ["", "", "_" + ch(r, EN_WORDS)])
|
| 110 |
+
v = ch(r, ["s", "word", "text", "name"])
|
| 111 |
+
c = ch(r, list(w.replace("_", "")))
|
| 112 |
+
d = ch(r, ["*", "#", "X", "0"])
|
| 113 |
+
i = r.randint(0, 3)
|
| 114 |
+
j = r.randint(i + 1, len(w))
|
| 115 |
+
pool = [f"{v}.upper()", f"{v}[::-1]", f"{v}.count({c!r})", f"{v}.replace({c!r}, {d!r})",
|
| 116 |
+
f"{v}.find({c!r})", f"{v}[{i}:{j}]", f"len({v})", f"{v}.capitalize()", f"{v}.split('_')",
|
| 117 |
+
f"{v}[-{r.randint(1, 4)}:]", f"{v}.index({c!r}) + len({v})"]
|
| 118 |
+
ops = r.sample(pool, 3)
|
| 119 |
+
code = body(f"{v} = {w!r}", *[f"print({o})" for o in ops])
|
| 120 |
+
return dict(kind="predict_output", key=(w, v, tuple(ops)), topic="strings", code=code)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def g_p_dict(r):
|
| 124 |
+
keys = r.sample(AR_NAMES, r.randint(3, 5))
|
| 125 |
+
d = {k: r.randint(0, 50) for k in keys}
|
| 126 |
+
k1 = ch(r, keys)
|
| 127 |
+
add = r.randint(1, 20)
|
| 128 |
+
new = ch(r, [n for n in AR_NAMES if n not in keys])
|
| 129 |
+
val = r.randint(0, 60)
|
| 130 |
+
v = ch(r, ["scores", "d", "marks", "points"])
|
| 131 |
+
last = ch(r, [f"print(sorted({v}.items(), key=lambda kv: (kv[1], kv[0]))[:2])",
|
| 132 |
+
f"print([k for k in {v} if {v}[k] > {r.randint(10, 40)}])",
|
| 133 |
+
f"print({v}.get({ch(r, AR_NAMES)!r}, -1))"])
|
| 134 |
+
code = body(f"{v} = {d!r}", f"{v}[{k1!r}] += {add}", f"{v}[{new!r}] = {val}", f"print(len({v}))",
|
| 135 |
+
f"print(max({v}, key={v}.get))", f"print(sum({v}.values()))", last)
|
| 136 |
+
return dict(kind="predict_output", key=(tuple(d.items()), k1, add, new, val, v, last), topic="dict", code=code)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def g_p_while(r):
|
| 140 |
+
v = ch(r, ["n", "x", "m"])
|
| 141 |
+
c = ch(r, ["steps", "count", "c"])
|
| 142 |
+
if r.random() < 0.5:
|
| 143 |
+
n, d, lim = r.randint(50, 100000), r.randint(2, 9), r.randint(0, 20)
|
| 144 |
+
code = body(f"{v} = {n}", f"{c} = 0", f"while {v} > {lim}:", f" {v} = {v} // {d}", f" {c} += 1",
|
| 145 |
+
f"print({v}, {c})")
|
| 146 |
+
key = ("div", n, d, lim, v, c)
|
| 147 |
+
else:
|
| 148 |
+
n = r.randint(2, 400)
|
| 149 |
+
code = body(f"{v} = {n}", f"{c} = 0", f"while {v} != 1:", f" if {v} % 2 == 0:", f" {v} = {v} // 2",
|
| 150 |
+
" else:", f" {v} = 3 * {v} + 1", f" {c} += 1", f"print({c})")
|
| 151 |
+
key = ("collatz", n, v, c)
|
| 152 |
+
return dict(kind="predict_output", key=key, topic="while_loop", code=code)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def g_p_comp(r):
|
| 156 |
+
a = r.randint(-6, 6)
|
| 157 |
+
b = a + r.randint(5, 15)
|
| 158 |
+
q = r.randint(2, 5)
|
| 159 |
+
rr = r.randint(0, q - 1)
|
| 160 |
+
m, c = r.randint(-3, 5), r.randint(-10, 10)
|
| 161 |
+
expr = ch(r, [f"x * {m} + {c}", f"x ** 2 - {abs(c)}", f"(x + {abs(c)}) // {q}"])
|
| 162 |
+
v = ch(r, ["res", "out", "vals"])
|
| 163 |
+
code = body(f"{v} = [{expr} for x in range({a}, {b}) if x % {q} == {rr}]", f"print({v})",
|
| 164 |
+
f"print(len({v}), sum({v}))")
|
| 165 |
+
return dict(kind="predict_output", key=(a, b, q, rr, expr, v), topic="list_comprehension", code=code)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def g_p_func(r):
|
| 169 |
+
A, D = r.randint(-5, 9), r.randint(0, 9)
|
| 170 |
+
p, q = r.randint(-10, 20), r.randint(-10, 20)
|
| 171 |
+
f = ch(r, ["f", "calc", "g", "compute", "h"])
|
| 172 |
+
code = body(f"def {f}(x, y={D}):", " if x > y:", f" return x * {A} - y", f" return x + y * {A}",
|
| 173 |
+
"", f"print({f}({p}))", f"print({f}({p}, {q}))", f"print({f}({f}({q}), {p}))")
|
| 174 |
+
return dict(kind="predict_output", key=(A, D, p, q, f), topic="functions", code=code)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def g_p_rec(r):
|
| 178 |
+
f = ch(r, ["f", "rec", "go", "calc"])
|
| 179 |
+
fam = r.randrange(4)
|
| 180 |
+
if fam == 0:
|
| 181 |
+
b, base, m, c = r.randint(0, 3), r.randint(1, 5), r.randint(1, 3), r.randint(-3, 4)
|
| 182 |
+
N = b + r.randint(1, 10)
|
| 183 |
+
code = body(f"def {f}(n):", f" if n <= {b}:", f" return {base}", f" return {m} * {f}(n - 1) + {c}",
|
| 184 |
+
"", f"print({f}({N}))")
|
| 185 |
+
key = (fam, b, base, m, c, N, f)
|
| 186 |
+
elif fam == 1:
|
| 187 |
+
N = r.randint(10, 10 ** 9)
|
| 188 |
+
code = body(f"def {f}(n):", " if n < 10:", " return n", f" return n % 10 + {f}(n // 10)", "",
|
| 189 |
+
f"print({f}({N}))", f"print({f}({f}({N})))")
|
| 190 |
+
key = (fam, N, f)
|
| 191 |
+
elif fam == 2:
|
| 192 |
+
n, k = r.randint(-5, 9), r.randint(0, 8)
|
| 193 |
+
code = body(f"def {f}(n, k):", " if k == 0:", " return 1", f" return n * {f}(n, k - 1)", "",
|
| 194 |
+
f"print({f}({n}, {k}))")
|
| 195 |
+
key = (fam, n, k, f)
|
| 196 |
+
else:
|
| 197 |
+
c, N = r.randint(0, 3), r.randint(2, 18)
|
| 198 |
+
code = body(f"def {f}(n):", " if n < 2:", f" return n + {c}", f" return {f}(n - 1) + {f}(n - 2)", "",
|
| 199 |
+
f"print({f}({N}))")
|
| 200 |
+
key = (fam, c, N, f)
|
| 201 |
+
return dict(kind="predict_output", key=key, topic="recursion", code=code)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def g_p_sort(r):
|
| 205 |
+
mode = r.randrange(3)
|
| 206 |
+
if mode == 0:
|
| 207 |
+
ws = r.sample(EN_WORDS, 5)
|
| 208 |
+
code = body(f"words = {ws!r}", "print(sorted(words, key=len))",
|
| 209 |
+
"print(sorted(words, key=lambda w: (len(w), w), reverse=True)[:3])")
|
| 210 |
+
key = (mode, tuple(ws))
|
| 211 |
+
elif mode == 1:
|
| 212 |
+
ns = ints(r, 5, 8, -20, 40)
|
| 213 |
+
c = r.randint(-10, 30)
|
| 214 |
+
code = body(f"nums = {ns}", f"print(sorted(nums, key=lambda x: (abs(x - {c}), x)))",
|
| 215 |
+
"print(sorted(nums, reverse=True)[:3])")
|
| 216 |
+
key = (mode, tuple(ns), c)
|
| 217 |
+
else:
|
| 218 |
+
ps = [(n, r.randint(0, 100)) for n in r.sample(AR_NAMES, 4)]
|
| 219 |
+
code = body(f"pairs = {ps!r}", "print(sorted(pairs, key=lambda p: (p[1], p[0])))",
|
| 220 |
+
"print([p[0] for p in sorted(pairs, key=lambda p: (-p[1], p[0]))][:2])")
|
| 221 |
+
key = (mode, tuple(ps))
|
| 222 |
+
return dict(kind="predict_output", key=key, topic="sorting", code=code)
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def g_p_arabic(r):
|
| 226 |
+
w = ch(r, AR_WORDS) + ch(r, ["", " " + ch(r, AR_WORDS)])
|
| 227 |
+
L = ch(r, list(w.replace(" ", "")) + AR_LETTERS[:5])
|
| 228 |
+
v = ch(r, ["w", "kalima", "text", "s"])
|
| 229 |
+
pool = [f"len({v})", f"{v}[::-1]", f"{v}.count({L!r})", f"{v}[0]", f"{v}[-1]", f"{v}.split()",
|
| 230 |
+
f"{v}.replace(' ', '-')", f"{L!r} in {v}", f"{v}.find({L!r})", f"len({v}.replace(' ', ''))"]
|
| 231 |
+
ops = r.sample(pool, 3)
|
| 232 |
+
code = body(f"{v} = {w!r}", *[f"print({o})" for o in ops])
|
| 233 |
+
return dict(kind="predict_output", key=(w, L, v, tuple(ops)), topic="arabic_text", code=code)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
# ---------------------------------------------------------------- write-a-function generators
|
| 237 |
+
# each returns dict(kind="write_function", key, topic, entry, ref, args (list of arg tuples), qs[3])
|
| 238 |
+
W = "write_function"
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def g_w_sum_mult(r):
|
| 242 |
+
a = r.randint(2, 9)
|
| 243 |
+
b = r.randint(a + 1, 15)
|
| 244 |
+
f = ch(r, ["sum_multiples", "multiples_total", "sum_div", "total_multiples", "add_multiples", "mult_sum"])
|
| 245 |
+
ref = body(f"def {f}(n):", f" return sum(x for x in range(1, n) if x % {a} == 0 or x % {b} == 0)")
|
| 246 |
+
args = [(n,) for n in [r.randint(20, 300)] + [r.randint(0, 300) for _ in range(5)] + [1]]
|
| 247 |
+
qs = [f"اكتب دالة بايثون باسم `{f}(n)` تُرجع مجموع الأعداد الصحيحة الموجبة الأصغر من n التي تقبل القسمة على {a} أو على {b}.",
|
| 248 |
+
f"أنشئ دالة `{f}(n)` تحسب مجموع كل عدد x حيث 1 ≤ x < n ويكون x من مضاعفات {a} أو من مضاعفات {b}، ثم تُرجع هذا المجموع.",
|
| 249 |
+
f"المطلوب دالة بايثون اسمها `{f}` تستقبل عددًا صحيحًا n، وتعيد حاصل جمع الأعداد من 1 إلى n−1 التي يقسمها {a} أو {b} دون باقٍ."]
|
| 250 |
+
return dict(kind=W, key=(a, b, f), topic="math", entry=f, ref=ref, args=args, qs=qs)
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def g_w_count_letter(r):
|
| 254 |
+
L = ch(r, AR_LETTERS)
|
| 255 |
+
mode = r.randrange(3)
|
| 256 |
+
f = ch(r, ["count_letter", "letter_count", "count_ar", "how_many", "count_in_text", "tally_letter", "count_hits", "letter_hits"])
|
| 257 |
+
expr = [f"text.count({L!r})", f"sum(1 for w in text.split() if {L!r} in w)",
|
| 258 |
+
f"sum(1 for w in text.split() if w.startswith({L!r}))"][mode]
|
| 259 |
+
what = [f"عدد مرات ظهور الحرف «{L}» في النص",
|
| 260 |
+
f"عدد الكلمات (المفصولة بمسافات) التي تحتوي على الحرف «{L}» مرة واحدة على الأقل",
|
| 261 |
+
f"عدد الكلمات (المفصولة بمسافات) التي تبدأ بالحرف «{L}»"][mode]
|
| 262 |
+
ref = body(f"def {f}(text):", f" return {expr}")
|
| 263 |
+
args = [(ar_sentence(r, 3, 8),)] + [(ar_sentence(r, 0, 8),) for _ in range(6)] + [("",)]
|
| 264 |
+
qs = [f"اكتب دالة بايثون `{f}(text)` تأخذ نصًا عربيًا وتُرجع {what}.",
|
| 265 |
+
f"أنشئ الدالة `{f}(text)` بحيث تُعيد {what}، حيث text سلسلة نصية بالعربية.",
|
| 266 |
+
f"عرّف دالة اسمها `{f}` تستقبل سلسلة نصية عربية text، والمطلوب أن تحسب وتُرجع {what}."]
|
| 267 |
+
return dict(kind=W, key=(L, mode, f), topic="arabic_text", entry=f, ref=ref, args=args, qs=qs)
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def g_w_reverse_words(r):
|
| 271 |
+
L = r.randint(1, 6)
|
| 272 |
+
sep = ch(r, [" ", "-", "_", "/", "|", ","])
|
| 273 |
+
f = ch(r, ["reverse_words", "flip_words", "rev_long_words", "backwards", "words_reversed", "invert_words", "rev_join", "mirror_words"])
|
| 274 |
+
ref = body(f"def {f}(s):", f" return {sep!r}.join([w for w in s.split() if len(w) >= {L}][::-1])")
|
| 275 |
+
args = [(en_sentence(r, 3, 8),)] + [(en_sentence(r, 0, 8),) for _ in range(6)]
|
| 276 |
+
qs = [f"اكتب دالة `{f}(s)` تأخذ جملة وتُرجع الكلمات التي طولها {L} أحرف أو أك��ر بترتيب معكوس، مفصولًا بينها بالفاصل {sep!r}.",
|
| 277 |
+
f"أنشئ دالة بايثون `{f}(s)`: قسّم الجملة s إلى كلمات (حسب المسافات)، احتفظ فقط بالكلمات التي لا يقل طولها عن {L}، اعكس ترتيبها ثم اجمعها في نص واحد بالفاصل {sep!r}.",
|
| 278 |
+
f"المطلوب دالة اسمها `{f}` تستقبل نصًا s، وتعيد نصًا يحتوي الكلمات التي عدد أحرفها ≥ {L} من آخرها إلى أولها، موصولة بالفاصل {sep!r}."]
|
| 279 |
+
return dict(kind=W, key=(L, sep, f), topic="strings", entry=f, ref=ref, args=args, qs=qs)
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def g_w_filter_range(r):
|
| 283 |
+
lo = r.randint(-20, 20)
|
| 284 |
+
hi = lo + r.randint(5, 40)
|
| 285 |
+
k = ch(r, [i for i in range(-5, 6) if i != 0])
|
| 286 |
+
f = ch(r, ["filter_range", "pick_between", "in_range_scaled", "select_range", "clip_scale", "between_times"])
|
| 287 |
+
ref = body(f"def {f}(xs):", f" return sorted(x * {k} for x in xs if {lo} <= x <= {hi})")
|
| 288 |
+
args = [(ints(r, 4, 10, lo - 10, hi + 10),)] + [(ints(r, 0, 10, -30, 60),) for _ in range(6)] + [([],)]
|
| 289 |
+
qs = [f"اكتب دالة `{f}(xs)` تأخذ قائمة أعداد صحيحة وتُرجع قائمة مرتبة تصاعديًا تحتوي حاصل ضرب كل عنصر يقع بين {lo} و{hi} (شاملًا الطرفين) في {k}.",
|
| 290 |
+
f"أنشئ دالة بايثون `{f}(xs)`: اختر من القائمة xs العناصر x التي تحقق {lo} ≤ x ≤ {hi}، اضرب كلًا منها في {k}، ثم أعِد النتائج مرتبة تصاعديًا.",
|
| 291 |
+
f"عرّف الدالة `{f}` التي تستقبل قائمة أعداد xs وتعيد قائمة تصاعدية بقيم x × {k} لكل عنصر x في المدى المغلق [{lo}, {hi}]."]
|
| 292 |
+
return dict(kind=W, key=(lo, hi, k, f), topic="lists", entry=f, ref=ref, args=args, qs=qs)
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def poly_str(a, b, c):
|
| 296 |
+
s = f"{a}x²"
|
| 297 |
+
s += f" {'+' if b >= 0 else '-'} {abs(b)}x"
|
| 298 |
+
s += f" {'+' if c >= 0 else '-'} {abs(c)}"
|
| 299 |
+
return s
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def g_w_poly(r):
|
| 303 |
+
a = ch(r, [i for i in range(-9, 10) if i != 0])
|
| 304 |
+
b, c = r.randint(-9, 9), r.randint(-9, 9)
|
| 305 |
+
f = ch(r, ["poly", "evaluate", "p", "quad", "eval_poly", "value_at"])
|
| 306 |
+
ref = body(f"def {f}(x):", f" return {a} * x ** 2 + ({b}) * x + ({c})")
|
| 307 |
+
args = [(x,) for x in [r.randint(1, 10)] + [r.randint(-20, 20) for _ in range(6)] + [0]]
|
| 308 |
+
ps = poly_str(a, b, c)
|
| 309 |
+
qs = [f"اكتب دالة بايثون `{f}(x)` تُرجع قيمة كثيرة الحدود {ps} عند العدد الصحيح x.",
|
| 310 |
+
f"أنشئ دالة `{f}(x)` تحسب المقدار {ps} لقيمة x المعطاة وتُرجع الناتج عددًا صحيحًا.",
|
| 311 |
+
f"عرّف الدالة `{f}` التي تستقبل عددًا صحيحًا x وتعيد قيمة الدالة التربيعية p(x) = {ps}."]
|
| 312 |
+
return dict(kind=W, key=(a, b, c, f), topic="math", entry=f, ref=ref, args=args, qs=qs)
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def g_w_digit_pow(r):
|
| 316 |
+
p, m = r.randint(1, 5), r.randint(2, 97)
|
| 317 |
+
f = ch(r, ["digit_power", "digits_mod", "sum_digit_pow", "dig_pow_mod", "digit_score", "pow_digits"])
|
| 318 |
+
ref = body(f"def {f}(n):", f" return sum(int(d) ** {p} for d in str(n)) % {m}")
|
| 319 |
+
args = [(n,) for n in [r.randint(100, 99999)] + [r.randint(0, 10 ** 6) for _ in range(6)] + [0]]
|
| 320 |
+
qs = [f"اكتب دالة `{f}(n)` تأخذ عددًا صحيحًا غير سالب n وتُرجع باقي قسمة (مجموع أرقام n كلٌّ مرفوع للأس {p}) على {m}.",
|
| 321 |
+
f"أنشئ دالة بايثون `{f}(n)`: ارفع كل رقم من أرقام n للقوة {p}، اجمع النتائج، ثم أعِد باقي قسمة المجموع على {m}.",
|
| 322 |
+
f"عرّف الدالة `{f}` التي تستقبل عددًا طبيعيًا n وتعيد (Σ رقم^{p} لكل أرقام n) mod {m}."]
|
| 323 |
+
return dict(kind=W, key=(p, m, f), topic="math", entry=f, ref=ref, args=args, qs=qs)
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
FIZZ = [("Fizz", "Buzz"), ("Ping", "Pong"), ("Foo", "Bar"), ("Tic", "Tac"), ("Hi", "Yo"), ("Red", "Blue"), ("Sun", "Moon")]
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
def g_w_fizz(r):
|
| 330 |
+
a = r.randint(2, 7)
|
| 331 |
+
b = r.randint(a + 1, 11)
|
| 332 |
+
w1, w2 = ch(r, FIZZ)
|
| 333 |
+
f = ch(r, ["fizz", "game", "fizzbuzz", "label_numbers", "play"])
|
| 334 |
+
ref = body(f"def {f}(n):", " out = []", " for i in range(1, n + 1):", " s = ''",
|
| 335 |
+
f" if i % {a} == 0:", f" s += {w1!r}", f" if i % {b} == 0:", f" s += {w2!r}",
|
| 336 |
+
" out.append(s or str(i))", " return out")
|
| 337 |
+
args = [(n,) for n in [r.randint(b, min(a * b + 2, 30))] + [r.randint(0, 25) for _ in range(4)]]
|
| 338 |
+
qs = [f"اكتب دالة `{f}(n)` تُرجع قائمة نصوص للأعداد من 1 إلى n: العدد الذي يقبل القسمة على {a} يُستبدل بـ {w1!r}، وعلى {b} بـ {w2!r}، وعلى كليهما بـ {(w1 + w2)!r}، وإلا يُكتب العدد نفسه نصًا.",
|
| 339 |
+
f"أنشئ دالة بايثون `{f}(n)` تبن�� قائمة لكل i من 1 إلى n: إن قَبِل i القسمة على {a} أضف {w1!r}، وإن قَبِلها على {b} أضف {w2!r} (فيصبح {(w1 + w2)!r} عند الاثنين)، وإن لم يتحقق أيٌّ منهما ضع str(i).",
|
| 340 |
+
f"عرّف الدالة `{f}` التي تستقبل n وتعيد قائمة بطول n: مضاعفات {a} تصبح {w1!r}، مضاعفات {b} تصبح {w2!r}، المضاعفات المشتركة تصبح {(w1 + w2)!r}، وبقية الأعداد تبقى أرقامًا بصيغة نص."]
|
| 341 |
+
return dict(kind=W, key=(a, b, w1, f), topic="loops", entry=f, ref=ref, args=args, qs=qs)
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
def g_w_caesar(r):
|
| 345 |
+
k = r.randint(1, 25)
|
| 346 |
+
enc = r.random() < 0.5
|
| 347 |
+
K = k if enc else -k
|
| 348 |
+
f = ch(r, ["caesar", "shift_text", "encode", "decode", "rotate_letters", "cipher", "shift_letters", "rot"])
|
| 349 |
+
ref = body(f"def {f}(s):", " out = []", " for c in s:", " if 'a' <= c <= 'z':",
|
| 350 |
+
f" out.append(chr((ord(c) - 97 + ({K})) % 26 + 97))", " else:", " out.append(c)",
|
| 351 |
+
" return ''.join(out)")
|
| 352 |
+
def samp():
|
| 353 |
+
t = en_sentence(r, 1, 5)
|
| 354 |
+
if r.random() < 0.4:
|
| 355 |
+
t += " " + ch(r, ["Hello", "OK", "2024", "A1", "!"])
|
| 356 |
+
return t
|
| 357 |
+
args = [(samp(),) for _ in range(6)] + [("",)]
|
| 358 |
+
dirw = f"إزاحة كل حرف إنجليزي صغير (a-z) {k} مواقع إلى الأمام في الأبجدية (مع الالتفاف من z إلى a)" if enc else \
|
| 359 |
+
f"إزاحة كل حرف إنجليزي صغير (a-z) {k} مواقع إلى الخلف في الأبجدية (مع الالتفاف من a إلى z)"
|
| 360 |
+
keep = "وتبقى بقية المحارف (الأحرف الكبيرة والأرقام والمسافات والرموز) كما هي"
|
| 361 |
+
qs = [f"اكتب دالة `{f}(s)` تُرجع النص الناتج عن {dirw}، {keep}.",
|
| 362 |
+
f"أنشئ دالة بايثون `{f}(s)` لتشفير قيصر: المطلوب {dirw}، {keep}.",
|
| 363 |
+
f"عرّف الدالة `{f}` التي تستقبل نصًا s وتعيد نصًا جديدًا بعد {dirw}، {keep}."]
|
| 364 |
+
return dict(kind=W, key=(k, enc, f), topic="strings", entry=f, ref=ref, args=args, qs=qs)
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def g_w_char_freq(r):
|
| 368 |
+
S = "".join(sorted(r.sample("abcdeghilmnorstu", r.randint(2, 4))))
|
| 369 |
+
f = ch(r, ["char_freq", "count_chars", "freq_of", "letter_stats", "char_counts", "tally"])
|
| 370 |
+
ref = body(f"def {f}(s):", f" return {{c: s.count(c) for c in {S!r}}}")
|
| 371 |
+
args = [(en_sentence(r, 1, 6),) for _ in range(6)] + [("",)]
|
| 372 |
+
lst = "، ".join(f"'{c}'" for c in S)
|
| 373 |
+
qs = [f"اكتب دالة `{f}(s)` تُرجع قاموسًا مفاتيحه المحارف {lst} وقيمة كل مفتاح عدد مرات ظهوره في النص s (حتى لو كان صفرًا).",
|
| 374 |
+
f"أنشئ دالة بايثون `{f}(s)` تعيد dict يربط كل محرف من المحارف {lst} بعدد تكراره في s، مع إدراج المحارف غير الموجودة بقيمة 0.",
|
| 375 |
+
f"عرّف الدالة `{f}` التي تستقبل سلسلة s وتعيد قاموس تكرارات للمحارف {lst} فقط (كل محرف ← عدد مرات وجوده، ولو كان 0)."]
|
| 376 |
+
return dict(kind=W, key=(S, f), topic="dict", entry=f, ref=ref, args=args, qs=qs)
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
def g_w_running(r):
|
| 380 |
+
Tm = r.randint(10, 200)
|
| 381 |
+
f = ch(r, ["running_sum", "capped_cumsum", "reset_sum", "cumulative", "acc_reset", "rolling_total"])
|
| 382 |
+
ref = body(f"def {f}(xs):", " out, s = [], 0", " for x in xs:", " s += x", f" if s > {Tm}:",
|
| 383 |
+
" s = 0", " out.append(s)", " return out")
|
| 384 |
+
args = [(ints(r, 5, 10, 1, Tm // 2 + 5),)] + [(ints(r, 0, 10, -10, Tm),) for _ in range(5)] + [([],)]
|
| 385 |
+
qs = [f"اكتب دالة `{f}(xs)` تُرجع قائمة المجاميع التراكمية لعناصر xs، مع قاعدة: إذا أصبح المجموع الجاري أكبر من {Tm} بعد إضافة عنصر فإنه يُصفَّر قبل تسجيله.",
|
| 386 |
+
f"أنشئ دالة بايثون `{f}(xs)`: ابدأ بمجموع s = 0، ولكل عنصر x أضِفه إلى s، فإن صار s > {Tm} اجعل s = 0، ثم أضف s إلى قائمة النتيجة. أعِد القائمة.",
|
| 387 |
+
f"عرّف الدالة `{f}` التي تستقبل قائمة أعداد وتعيد مجاميعها التراكمية، بحيث يُعاد المجموع إلى الصفر كلما تجاوز {Tm} (القيمة المسجلة حينها 0)."]
|
| 388 |
+
return dict(kind=W, key=(Tm, f), topic="lists", entry=f, ref=ref, args=args, qs=qs)
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def g_w_coprime(r):
|
| 392 |
+
k = r.randint(2, 90)
|
| 393 |
+
f = ch(r, ["count_coprime", "coprimes", "phi_upto", "rel_prime_count", "coprime_count", "count_gcd1"])
|
| 394 |
+
ref = body(f"def {f}(n):", " from math import gcd", f" return sum(1 for i in range(1, n + 1) if gcd(i, {k}) == 1)")
|
| 395 |
+
args = [(n,) for n in [r.randint(10, 150)] + [r.randint(0, 200) for _ in range(5)] + [1]]
|
| 396 |
+
qs = [f"اكتب دالة `{f}(n)` تُرجع عدد الأعداد الصحيحة i في المدى من 1 إلى n (شاملًا) التي تكون أولية نسبيًا مع {k}، أي أن القاسم المشترك الأكبر لها مع {k} يساوي 1.",
|
| 397 |
+
f"أنشئ دالة بايثون `{f}(n)` تعدّ قيم i حيث 1 ≤ i ≤ n و gcd(i, {k}) = 1، ثم تُرجع العدد.",
|
| 398 |
+
f"عرّف الدالة `{f}` التي تستقبل n وتعيد كم عددًا بين 1 وn لا يشترك مع العدد {k} في أي قاسم أكبر من 1."]
|
| 399 |
+
return dict(kind=W, key=(k, f), topic="math", entry=f, ref=ref, args=args, qs=qs)
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
# ---------------------------------------------------------------- fix-the-bug generators
|
| 403 |
+
# return dict(kind="fix_bug", ..., buggy=<code>); the buggy code must fail >=1 hidden test
|
| 404 |
+
FX = "fix_bug"
|
| 405 |
+
FIXQ = ["الدالة التالية يُفترض أن {spec}، لكنها تحتوي على خطأ برمجي. أصلح الخطأ واكتب الدالة الصحيحة كاملة.\n```python\n{code}\n```",
|
| 406 |
+
"في الشيفرة الآتية خطأ يجعل الدالة لا تعمل كما يجب. المطلوب منها أن {spec}. اكتشف الخطأ وأعد كتابة الدالة بعد إصلاحه.\n```python\n{code}\n```",
|
| 407 |
+
"صحّح الدالة التالية لكي {spec}؛ فهي حاليًا تُعطي نتائج خاطئة في بعض الحالات. اكتب النسخة المصحّحة كاملة.\n```python\n{code}\n```"]
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def fix_qs(spec, buggy):
|
| 411 |
+
return [t.format(spec=spec, code=buggy) for t in FIXQ]
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
def g_f_power_sum(r):
|
| 415 |
+
p, c = r.randint(1, 5), r.randint(1, 12)
|
| 416 |
+
f = ch(r, ["power_sum", "weighted_sum", "sum_powers", "series", "total_pow", "pow_total", "sum_terms", "scaled_powers"])
|
| 417 |
+
bug = r.randrange(3)
|
| 418 |
+
rng = ["range(1, n + 1)", "range(1, n)", "range(0, n)", "range(1, n + 1)"]
|
| 419 |
+
upd = ["+=", "+=", "+=", "="]
|
| 420 |
+
def mk(i):
|
| 421 |
+
return body(f"def {f}(n):", " total = 0", f" for i in {rng[i]}:", f" total {upd[i]} {c} * i ** {p}",
|
| 422 |
+
" return total")
|
| 423 |
+
ref, buggy = mk(0), mk(bug + 1)
|
| 424 |
+
spec = f"تُرجع مجموع {c} × i^{p} لكل عدد صحيح i من 1 إلى n (شاملًا n)"
|
| 425 |
+
args = [(n,) for n in [r.randint(3, 8)] + [r.randint(0, 15) for _ in range(4)] + [1, 0]]
|
| 426 |
+
return dict(kind=FX, key=(p, c, f), topic="loops", entry=f, ref=ref, buggy=buggy, args=args,
|
| 427 |
+
qs=fix_qs(spec, buggy))
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
def g_f_max_div(r):
|
| 431 |
+
d = r.randint(2, 12)
|
| 432 |
+
v = ch(r, ["xs", "nums", "values", "arr"])
|
| 433 |
+
f = ch(r, ["max_multiple", "largest_div", "best_multiple", "top_divisible", "max_div", "biggest_mult", "max_of_div", "find_max_div"])
|
| 434 |
+
bug = r.randrange(3)
|
| 435 |
+
def mk(i):
|
| 436 |
+
ini = ["None", "0", "None", "None"][i]
|
| 437 |
+
cond = [f"x % {d} == 0 and (best is None or x > best)", f"x % {d} == 0 and (best is None or x > best)",
|
| 438 |
+
f"x % {d} == 0 and (best is None or x < best)", f"x % {d} != 0 and (best is None or x > best)"][i]
|
| 439 |
+
return body(f"def {f}({v}):", f" best = {ini}", f" for x in {v}:", f" if {cond}:", " best = x",
|
| 440 |
+
" return best")
|
| 441 |
+
ref, buggy = mk(0), mk(bug + 1)
|
| 442 |
+
spec = f"تُرجع أكبر عنصر في القائمة {v} يقبل القسمة على {d}، أو None إذا لم يوجد مثل هذا العنصر"
|
| 443 |
+
args = [(ints(r, 4, 9, -30, 60),), ([-d * r.randint(1, 5) for _ in range(3)],), ([d * k + 1 for k in range(r.randint(1, 4))],),
|
| 444 |
+
(ints(r, 0, 9, -40, 40),), (ints(r, 3, 9, -50, 50),), ([],)]
|
| 445 |
+
return dict(kind=FX, key=(d, v, f), topic="lists", entry=f, ref=ref, buggy=buggy, args=args, qs=fix_qs(spec, buggy))
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
def g_f_starts_with(r):
|
| 449 |
+
L = ch(r, AR_LETTERS)
|
| 450 |
+
f = ch(r, ["count_start", "starts_count", "words_starting", "count_prefix", "begin_count", "count_initial", "prefix_hits", "lead_count"])
|
| 451 |
+
v = ch(r, ["text", "s", "sentence", "line"])
|
| 452 |
+
bug = r.randrange(3)
|
| 453 |
+
def mk(i):
|
| 454 |
+
loop = f" for w in {v}:" if i == 3 else f" for w in {v}.split():"
|
| 455 |
+
cond = [f"w.startswith({L!r})", f"w.endswith({L!r})", f"{L!r} in w", f"w.startswith({L!r})"][i]
|
| 456 |
+
return body(f"def {f}({v}):", " count = 0", loop, f" if {cond}:", " count += 1", " return count")
|
| 457 |
+
ref, buggy = mk(0), mk(bug + 1)
|
| 458 |
+
spec = f"تُرجع عدد الكلمات (المفصولة بمسافات) في النص العربي {v} التي تبدأ بالحرف «{L}»"
|
| 459 |
+
starts = [w for w in AR_WORDS if w.startswith(L)] or [L + "مل"]
|
| 460 |
+
def sent():
|
| 461 |
+
ws = [ch(r, AR_WORDS) for _ in range(r.randint(2, 6))] + [ch(r, starts) for _ in range(r.randint(0, 2))]
|
| 462 |
+
r.shuffle(ws)
|
| 463 |
+
return " ".join(ws)
|
| 464 |
+
args = [(sent(),) for _ in range(6)] + [("",)]
|
| 465 |
+
return dict(kind=FX, key=(L, v, f), topic="arabic_text", entry=f, ref=ref, buggy=buggy, args=args, qs=fix_qs(spec, buggy))
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
# ---------------------------------------------------------------- complete-the-function generators
|
| 469 |
+
CP = "complete_function"
|
| 470 |
+
COMPQ = ["أكمل الدالة التالية بوضع التعبير المناسب مكان ____ بحيث {spec}، ثم اكتب الدالة كاملة.\n```python\n{code}\n```",
|
| 471 |
+
"في الدالة الآتية جزء ناقص مكتوب ____. املأه لكي {spec}، واكتب الدالة بعد إكمالها.\n```python\n{code}\n```",
|
| 472 |
+
"المطلوب إكمال الشيفرة التالية (استبدل ____ بالتعبير الصحيح) حتى {spec}. اكتب الحل كاملًا.\n```python\n{code}\n```"]
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
def comp_qs(spec, skel):
|
| 476 |
+
return [t.format(spec=spec, code=skel) for t in COMPQ]
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
def g_c_count_div(r):
|
| 480 |
+
d, e = r.sample(range(2, 10), 2)
|
| 481 |
+
f = ch(r, ["count_div", "count_special", "only_div", "count_matching", "div_not", "count_sel", "tally_div", "how_many_div"])
|
| 482 |
+
def mk(cond):
|
| 483 |
+
return body(f"def {f}(xs):", " count = 0", " for x in xs:", f" if {cond}:", " count += 1",
|
| 484 |
+
" return count")
|
| 485 |
+
ref, skel = mk(f"x % {d} == 0 and x % {e} != 0"), mk("____")
|
| 486 |
+
spec = f"تُرجع الدالة عدد عناصر xs التي تقبل القسمة على {d} ولا تقبل القسمة على {e}"
|
| 487 |
+
args = [(ints(r, 6, 12, 0, 90),)] + [(ints(r, 0, 12, -40, 90),) for _ in range(5)] + [([],)]
|
| 488 |
+
return dict(kind=CP, key=(d, e, f), topic="loops", entry=f, ref=ref, args=args, qs=comp_qs(spec, skel))
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
def g_c_rotate(r):
|
| 492 |
+
k = r.randint(1, 20)
|
| 493 |
+
left = r.random() < 0.5
|
| 494 |
+
f = ch(r, ["rotate", "shift_list", "rotate_list", "cycle", "spin", "roll", "turn_list", "rotate_by"])
|
| 495 |
+
v = ch(r, ["xs", "items", "lst", "arr"])
|
| 496 |
+
def mk(ret):
|
| 497 |
+
return body(f"def {f}({v}):", f" if not {v}:", " return []", f" k = {k} % len({v})", f" return {ret}")
|
| 498 |
+
ref = mk(f"{v}[k:] + {v}[:k]" if left else f"{v}[len({v}) - k:] + {v}[:len({v}) - k]")
|
| 499 |
+
skel = mk("____")
|
| 500 |
+
spec = (f"تُرجع الدالة القائمة بعد تدويرها {k} مواقع إلى اليسار (العنصر الأول ينتقل إلى النهاية في كل خطوة)" if left else
|
| 501 |
+
f"تُرجع الدالة القائمة بعد تدويرها {k} مواقع إلى اليمين (العنصر الأخير ينتقل إلى البداية في كل خطوة)")
|
| 502 |
+
args = [(ints(r, 3, 8, 0, 50),)] + [(ints(r, 1, 12, -9, 50),) for _ in range(5)] + [([],)]
|
| 503 |
+
return dict(kind=CP, key=(k, left, v, f), topic="lists", entry=f, ref=ref, args=args, qs=comp_qs(spec, skel))
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
PRIMES = [7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 997, 1009, 10007]
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
def g_c_rec_mod(r):
|
| 510 |
+
s, M = r.randint(1, 4), ch(r, PRIMES)
|
| 511 |
+
f = ch(r, ["multi_fact", "fact_mod", "step_product", "prod_mod", "mfact", "rec_prod"])
|
| 512 |
+
def mk(ret):
|
| 513 |
+
return body(f"def {f}(n):", " if n <= 0:", " return 1", f" return {ret}")
|
| 514 |
+
ref, skel = mk(f"(n * {f}(n - {s})) % {M}"), mk("____")
|
| 515 |
+
spec = (f"تحسب الدالة تعاوديًا (بالاستدعاء الذاتي) حاصل الضرب n × (n−{s}) × (n−{2 * s}) × … للحدود الموجبة، "
|
| 516 |
+
f"مع أخذ باقي القسمة على {M} في كل خطوة (وتُرجع 1 عندما n ≤ 0)")
|
| 517 |
+
args = [(n,) for n in [r.randint(3, 12)] + [r.randint(0, 60) for _ in range(5)] + [0]]
|
| 518 |
+
return dict(kind=CP, key=(s, M, f), topic="recursion", entry=f, ref=ref, args=args, qs=comp_qs(spec, skel))
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
GENS = [g_p_slice, g_p_loop, g_p_str, g_p_dict, g_p_while, g_p_comp, g_p_func, g_p_rec, g_p_sort, g_p_arabic,
|
| 522 |
+
g_w_sum_mult, g_w_count_letter, g_w_reverse_words, g_w_filter_range, g_w_poly, g_w_digit_pow, g_w_fizz,
|
| 523 |
+
g_w_caesar, g_w_char_freq, g_w_running, g_w_coprime,
|
| 524 |
+
g_f_power_sum, g_f_max_div, g_f_starts_with,
|
| 525 |
+
g_c_count_div, g_c_rotate, g_c_rec_mod]
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
# ---------------------------------------------------------------- normalisation / leakage (as A10)
|
| 529 |
+
_DIAC = re.compile(r"[ؐ-ًؚ-ٰٟۖ-ۭـ]")
|
| 530 |
+
_AR_DIG = str.maketrans("٠١٢٣٤٥٦٧٨٩۰۱۲۳۴۵۶۷۸۹", "01234567890123456789")
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
def norm(s):
|
| 534 |
+
s = _DIAC.sub("", s or "").translate(_AR_DIG)
|
| 535 |
+
s = re.sub("[إأآٱ]", "ا", s).replace("ى", "ي").replace("ة", "ه").replace("ؤ", "و").replace("ئ", "ي")
|
| 536 |
+
s = re.sub(r"[^\w]+", " ", s.lower())
|
| 537 |
+
return re.sub(r"\s+", " ", s).strip()
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
def code_norm(s):
|
| 541 |
+
return re.sub(r"\s+", " ", s or "").strip()
|
| 542 |
+
|
| 543 |
+
|
| 544 |
+
def question_of(prompt):
|
| 545 |
+
p = prompt or ""
|
| 546 |
+
if p.startswith(HEAD):
|
| 547 |
+
p = p[len(HEAD):]
|
| 548 |
+
return p.rsplit(TAIL, 1)[0].strip()
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
EXS = ["\nمثال: `{call}` يجب أن تُرجع `{res}`.",
|
| 552 |
+
"\nللتوضيح: الاستدعاء `{call}` يُرجع `{res}`.",
|
| 553 |
+
"\nمثال: `{call} == {res}`"]
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
def call_str(entry, args):
|
| 557 |
+
return f"{entry}({', '.join(repr(a) for a in args)})"
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
def _passes(src, entry, args, results):
|
| 561 |
+
"""in-process screen (build-time only, our own template code): does `src` reproduce `results`?"""
|
| 562 |
+
try:
|
| 563 |
+
ns = {}
|
| 564 |
+
exec(src, ns)
|
| 565 |
+
fn = ns[entry]
|
| 566 |
+
return all(fn(*copy.deepcopy(a)) == res for a, res in zip(args, results))
|
| 567 |
+
except Exception:
|
| 568 |
+
return False
|
| 569 |
+
|
| 570 |
+
|
| 571 |
+
def materialize(gname, spec, ti):
|
| 572 |
+
"""Build an item (without subprocess gold) for phrasing ti; None if the instance is unusable."""
|
| 573 |
+
kind = spec["kind"]
|
| 574 |
+
base = {"task": "code", "src": "a11_code_gen", "lang": "python", "kind": kind, "topic": spec["topic"],
|
| 575 |
+
"template": f"{gname}#{ti}"}
|
| 576 |
+
if kind == "predict_output":
|
| 577 |
+
q = PQ[ti].format(code=spec["code"])
|
| 578 |
+
base.update(code=spec["code"])
|
| 579 |
+
else:
|
| 580 |
+
ns = {}
|
| 581 |
+
try:
|
| 582 |
+
exec(spec["ref"], ns)
|
| 583 |
+
fn = ns[spec["entry"]]
|
| 584 |
+
results = [fn(*copy.deepcopy(a)) for a in spec["args"]]
|
| 585 |
+
except Exception:
|
| 586 |
+
return None
|
| 587 |
+
for res in results: # must round-trip through repr
|
| 588 |
+
try:
|
| 589 |
+
if eval(repr(res)) != res:
|
| 590 |
+
return None
|
| 591 |
+
except Exception:
|
| 592 |
+
return None
|
| 593 |
+
if kind == "fix_bug" and _passes(spec["buggy"], spec["entry"], spec["args"], results):
|
| 594 |
+
return None # bug not exposed by the tests -> reject instance
|
| 595 |
+
tests = [f"assert {call_str(spec['entry'], a)} == {res!r}" for a, res in zip(spec["args"], results)]
|
| 596 |
+
q = spec["qs"][ti] + EXS[ti].format(call=call_str(spec["entry"], spec["args"][0]), res=repr(results[0]))
|
| 597 |
+
base.update(entry=spec["entry"], reference=spec["ref"], tests=tests, test_code="\n".join(tests),
|
| 598 |
+
answer=spec["ref"], completion=f" ```python\n{spec['ref']}\n```\n")
|
| 599 |
+
if kind == "fix_bug":
|
| 600 |
+
base["buggy"] = spec["buggy"]
|
| 601 |
+
base["prompt"] = HEAD + q + TAIL
|
| 602 |
+
base["qhash"] = hashlib.sha1(q.strip().encode("utf-8")).hexdigest()[:16]
|
| 603 |
+
return base
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
def verify(item):
|
| 607 |
+
"""Subprocess gold/verification. Returns (ok, message)."""
|
| 608 |
+
k = item["kind"]
|
| 609 |
+
if k == "predict_output":
|
| 610 |
+
rc, out, err = run_py(item["code"], timeout=BUILD_TIMEOUT)
|
| 611 |
+
if rc != 0:
|
| 612 |
+
return False, f"snippet rc={rc} err={err[-200:]}"
|
| 613 |
+
out = out.rstrip("\n")
|
| 614 |
+
if not out.strip() or len(out) > 600:
|
| 615 |
+
return False, f"bad output len={len(out)}"
|
| 616 |
+
item["answer"] = out
|
| 617 |
+
item["completion"] = f" الناتج:\n```text\n{out}\n```\n"
|
| 618 |
+
return True, ""
|
| 619 |
+
rc, out, err = run_py(program_with_tests(item["reference"], item["test_code"]), timeout=BUILD_TIMEOUT)
|
| 620 |
+
if not (rc == 0 and SENTINEL in out):
|
| 621 |
+
return False, f"reference failed rc={rc} err={err[-200:]}"
|
| 622 |
+
if k == "fix_bug":
|
| 623 |
+
rc, out, err = run_py(program_with_tests(item["buggy"], item["test_code"]), timeout=BUILD_TIMEOUT)
|
| 624 |
+
if rc == 0 and SENTINEL in out:
|
| 625 |
+
return False, "buggy version passes the tests"
|
| 626 |
+
return True, ""
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
def main():
|
| 630 |
+
t0 = time.time()
|
| 631 |
+
r = random.Random(SEED)
|
| 632 |
+
train, exam = [], []
|
| 633 |
+
used_keys = collections.defaultdict(set)
|
| 634 |
+
seen_norm = set()
|
| 635 |
+
for g in GENS:
|
| 636 |
+
name = g.__name__[2:]
|
| 637 |
+
for split, need, phr in (("train", N_TRAIN_PER_GEN, None), ("exam", N_EXAM_PER_GEN, 2)):
|
| 638 |
+
tries = cnt = 0
|
| 639 |
+
while cnt < need:
|
| 640 |
+
tries += 1
|
| 641 |
+
if tries > 200000:
|
| 642 |
+
raise SystemExit(f"cannot fill {split} for {name} ({cnt}/{need})")
|
| 643 |
+
spec = g(r)
|
| 644 |
+
key = spec["key"]
|
| 645 |
+
if split == "exam" and key in used_keys[name]:
|
| 646 |
+
continue
|
| 647 |
+
ti = r.randrange(2) if phr is None else phr
|
| 648 |
+
it = materialize(name, spec, ti)
|
| 649 |
+
if it is None:
|
| 650 |
+
continue
|
| 651 |
+
n = norm(question_of(it["prompt"]))
|
| 652 |
+
if n in seen_norm:
|
| 653 |
+
continue
|
| 654 |
+
seen_norm.add(n)
|
| 655 |
+
used_keys[name if split == "train" else name + "#exam"].add(key)
|
| 656 |
+
(train if split == "train" else exam).append(it)
|
| 657 |
+
cnt += 1
|
| 658 |
+
print(f"[gen] {name}: train={N_TRAIN_PER_GEN} exam={N_EXAM_PER_GEN} keys_train={len(used_keys[name])}", flush=True)
|
| 659 |
+
print(f"[gen] done in {time.time() - t0:.1f}s; verifying {len(train) + len(exam)} items in subprocesses "
|
| 660 |
+
f"(workers={WORKERS})", flush=True)
|
| 661 |
+
|
| 662 |
+
# ---- subprocess verification / gold outputs
|
| 663 |
+
allitems = train + exam
|
| 664 |
+
t1 = time.time()
|
| 665 |
+
fails = []
|
| 666 |
+
with ThreadPoolExecutor(max_workers=WORKERS) as ex:
|
| 667 |
+
for i, (ok, msg) in enumerate(ex.map(verify, allitems)):
|
| 668 |
+
if not ok:
|
| 669 |
+
fails.append((allitems[i]["template"], msg))
|
| 670 |
+
if (i + 1) % 1000 == 0:
|
| 671 |
+
print(f"[verify] {i + 1}/{len(allitems)} fails={len(fails)} {time.time() - t1:.0f}s", flush=True)
|
| 672 |
+
vstats = collections.Counter(x["kind"] for x in allitems)
|
| 673 |
+
if fails:
|
| 674 |
+
for f_ in fails[:20]:
|
| 675 |
+
print("[FAIL]", f_)
|
| 676 |
+
raise SystemExit(f"VERIFY FAILED: {len(fails)} items")
|
| 677 |
+
r.shuffle(train)
|
| 678 |
+
r.shuffle(exam)
|
| 679 |
+
|
| 680 |
+
# ---- leakage
|
| 681 |
+
def sets(items):
|
| 682 |
+
ps = [x["prompt"] for x in items]
|
| 683 |
+
qs = [question_of(p) for p in ps]
|
| 684 |
+
return {"exact": set(ps), "norm": {norm(p) for p in ps}, "qnorm": {norm(q) for q in qs},
|
| 685 |
+
"qhash": {hashlib.sha1(q.encode("utf-8")).hexdigest()[:16] for q in qs},
|
| 686 |
+
"code": {code_norm(x.get("code") or x.get("reference")) for x in items}}
|
| 687 |
+
|
| 688 |
+
tr_s, ex_s = sets(train), sets(exam)
|
| 689 |
+
leak = {k: len(tr_s[k] & ex_s[k]) for k in tr_s}
|
| 690 |
+
leak["param_combos"] = sum(len(used_keys[g.__name__[2:]] & used_keys[g.__name__[2:] + "#exam"]) for g in GENS)
|
| 691 |
+
dup_train = len(train) - len({norm(question_of(x["prompt"])) for x in train})
|
| 692 |
+
total = sum(leak.values())
|
| 693 |
+
|
| 694 |
+
trp, exp_ = os.path.join(T, f"{OUT}_train.jsonl"), os.path.join(T, f"{OUT}_exam.jsonl")
|
| 695 |
+
with open(trp, "w", encoding="utf-8", newline="\n") as f:
|
| 696 |
+
for x in train:
|
| 697 |
+
f.write(json.dumps(x, ensure_ascii=False) + "\n")
|
| 698 |
+
with open(exp_, "w", encoding="utf-8", newline="\n") as f:
|
| 699 |
+
for x in exam:
|
| 700 |
+
f.write(json.dumps(x, ensure_ascii=False) + "\n")
|
| 701 |
+
sha = lambda p: hashlib.sha256(open(p, "rb").read()).hexdigest()[:16]
|
| 702 |
+
lines = [
|
| 703 |
+
f"A11 code | seed={SEED} | generators={len(GENS)} | phrasings train=0,1 exam=2 | python={sys.version.split()[0]}",
|
| 704 |
+
f"train={len(train)} exam={len(exam)}",
|
| 705 |
+
f"train by kind {dict(sorted(collections.Counter(x['kind'] for x in train).items()))}",
|
| 706 |
+
f"exam by kind {dict(sorted(collections.Counter(x['kind'] for x in exam).items()))}",
|
| 707 |
+
f"train by topic {dict(sorted(collections.Counter(x['topic'] for x in train).items()))}",
|
| 708 |
+
f"exam by topic {dict(sorted(collections.Counter(x['topic'] for x in exam).items()))}",
|
| 709 |
+
f"verified in subprocess: {dict(vstats)} | fails=0 | fix_bug buggy-versions all fail tests | "
|
| 710 |
+
f"verify_time={time.time() - t1:.0f}s",
|
| 711 |
+
f"leakage train_vs_exam {leak} | train_internal_dups={dup_train}",
|
| 712 |
+
f"LEAKAGE={total}",
|
| 713 |
+
f"{OUT}_train sha256[:16]={sha(trp)} | {OUT}_exam sha256[:16]={sha(exp_)}",
|
| 714 |
+
]
|
| 715 |
+
msg = "\n".join(lines)
|
| 716 |
+
print(msg)
|
| 717 |
+
open(os.path.join(T, f"{OUT}_build.log"), "w", encoding="utf-8").write(msg + "\n")
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-8 -*-
|
| 2 |
+
"""check_a11.py - independent re-verification of SUPERBRAIN-1 Packet A11 (Arabic-instruction Python coding).
|
| 3 |
+
|
| 4 |
+
Checks (exit 0 only if all pass):
|
| 5 |
+
1. counts: train == 6021, exam == 1026 (A11_NTRAIN/A11_NEXAM x 27 generators), 27 generators present in both,
|
| 6 |
+
schema fields present, no duplicate prompts inside a split.
|
| 7 |
+
2. reference solutions: random sample (>=300 train + 100 exam code items) re-run through a11_score.score()
|
| 8 |
+
on their gold completion (subprocess + hidden tests, 5 s timeout) -> must be 100%;
|
| 9 |
+
fix_bug items in the sample: the buggy version must FAIL.
|
| 10 |
+
3. predict_output: random sample (150 train + 50 exam) snippets re-executed in a subprocess -> stdout must
|
| 11 |
+
equal the stored answer; the gold completion and a bare "الناتج: ..." answer must score True.
|
| 12 |
+
4. negative control: completions of OTHER items must score < 5%.
|
| 13 |
+
5. leakage train<->exam: exact / normalized prompt, normalized question, question hash, code -> all 0.
|
| 14 |
+
"""
|
| 15 |
+
import os, sys, json, random, hashlib, collections, time
|
| 16 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 17 |
+
|
| 18 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = ""
|
| 19 |
+
try:
|
| 20 |
+
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
| 21 |
+
except Exception:
|
| 22 |
+
pass
|
| 23 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 24 |
+
from a11_score import score, run_py, norm_out, CODE_KINDS # noqa: E402
|
| 25 |
+
from build_packet_a11 import norm, question_of, code_norm, GENS # noqa: E402
|
| 26 |
+
|
| 27 |
+
T = os.environ.get("A11_DIR", r"E:\ABU\02_PROJECTS\AHMAD-1\train")
|
| 28 |
+
NG = len(GENS)
|
| 29 |
+
EXP_TRAIN = NG * int(os.environ.get("A11_NTRAIN", "223"))
|
| 30 |
+
EXP_EXAM = NG * int(os.environ.get("A11_NEXAM", "38"))
|
| 31 |
+
N_REF_TRAIN, N_REF_EXAM, N_PRED_TRAIN, N_PRED_EXAM, N_NEG = 300, 100, 150, 50, 100
|
| 32 |
+
WORKERS = int(os.environ.get("A11_WORKERS", "6"))
|
| 33 |
+
FIELDS = ["task", "src", "kind", "topic", "template", "prompt", "completion", "answer", "qhash"]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def load(p):
|
| 37 |
+
with open(p, encoding="utf-8") as f:
|
| 38 |
+
return [json.loads(l) for l in f if l.strip()]
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def main():
|
| 42 |
+
t0 = time.time()
|
| 43 |
+
ok_all = True
|
| 44 |
+
tr = load(os.path.join(T, "packet_a11_train.jsonl"))
|
| 45 |
+
ex = load(os.path.join(T, "packet_a11_exam.jsonl"))
|
| 46 |
+
|
| 47 |
+
# 1. counts / schema
|
| 48 |
+
gtr = {x["template"].split("#")[0] for x in tr}
|
| 49 |
+
gex = {x["template"].split("#")[0] for x in ex}
|
| 50 |
+
miss = sum(1 for x in tr + ex for k in FIELDS if k not in x) + \
|
| 51 |
+
sum(1 for x in tr + ex if x["kind"] in CODE_KINDS and not x.get("test_code"))
|
| 52 |
+
dups = (len(tr) - len({x["prompt"] for x in tr})) + (len(ex) - len({x["prompt"] for x in ex}))
|
| 53 |
+
exam_phr = collections.Counter(x["template"].split("#")[1] for x in ex)
|
| 54 |
+
c_ok = (len(tr) == EXP_TRAIN and len(ex) == EXP_EXAM and len(gtr) == NG and len(gex) == NG
|
| 55 |
+
and miss == 0 and dups == 0 and set(exam_phr) == {"2"})
|
| 56 |
+
print(f"[counts] train={len(tr)} (expect {EXP_TRAIN}) exam={len(ex)} (expect {EXP_EXAM}) "
|
| 57 |
+
f"generators train={len(gtr)} exam={len(gex)} (expect {NG}) missing_fields={miss} dup_prompts={dups} "
|
| 58 |
+
f"exam_phrasings={dict(exam_phr)} -> {'OK' if c_ok else 'FAIL'}")
|
| 59 |
+
print(f"[counts] train by kind {dict(sorted(collections.Counter(x['kind'] for x in tr).items()))}")
|
| 60 |
+
print(f"[counts] exam by kind {dict(sorted(collections.Counter(x['kind'] for x in ex).items()))}")
|
| 61 |
+
ok_all &= c_ok
|
| 62 |
+
|
| 63 |
+
rng = random.Random(1111)
|
| 64 |
+
code_tr = [x for x in tr if x["kind"] in CODE_KINDS]
|
| 65 |
+
code_ex = [x for x in ex if x["kind"] in CODE_KINDS]
|
| 66 |
+
pred_tr = [x for x in tr if x["kind"] == "predict_output"]
|
| 67 |
+
pred_ex = [x for x in ex if x["kind"] == "predict_output"]
|
| 68 |
+
ref_sample = rng.sample(code_tr, N_REF_TRAIN) + rng.sample(code_ex, N_REF_EXAM)
|
| 69 |
+
pred_sample = rng.sample(pred_tr, N_PRED_TRAIN) + rng.sample(pred_ex, N_PRED_EXAM)
|
| 70 |
+
|
| 71 |
+
# 2. reference solutions pass hidden tests; buggy versions fail
|
| 72 |
+
def ref_job(x):
|
| 73 |
+
good = score(x["completion"], x, timeout=5.0)
|
| 74 |
+
bad = None
|
| 75 |
+
if x["kind"] == "fix_bug":
|
| 76 |
+
bad = score(f"```python\n{x['buggy']}\n```", x, timeout=5.0)
|
| 77 |
+
return good, bad
|
| 78 |
+
|
| 79 |
+
with ThreadPoolExecutor(WORKERS) as pool:
|
| 80 |
+
res = list(pool.map(ref_job, ref_sample))
|
| 81 |
+
n_ref = len(res)
|
| 82 |
+
ref_pass = sum(1 for g, _ in res if g)
|
| 83 |
+
fix = [b for _, b in res if b is not None]
|
| 84 |
+
fix_bad_pass = sum(1 for b in fix if b)
|
| 85 |
+
by_kind = collections.Counter(x["kind"] for x in ref_sample)
|
| 86 |
+
r_ok = ref_pass == n_ref and fix_bad_pass == 0
|
| 87 |
+
print(f"[reference] sample={n_ref} {dict(by_kind)} pass={ref_pass}/{n_ref} ({100 * ref_pass / n_ref:.2f}%) | "
|
| 88 |
+
f"fix_bug buggy versions passing={fix_bad_pass}/{len(fix)} (must be 0) -> {'OK' if r_ok else 'FAIL'}")
|
| 89 |
+
ok_all &= r_ok
|
| 90 |
+
|
| 91 |
+
# 3. predict_output gold re-execution
|
| 92 |
+
def pred_job(x):
|
| 93 |
+
rc, out, _ = run_py(x["code"], timeout=5.0)
|
| 94 |
+
same = rc == 0 and norm_out(out) == norm_out(x["answer"])
|
| 95 |
+
return same, score(x["completion"], x), score("الناتج: " + x["answer"], x)
|
| 96 |
+
|
| 97 |
+
with ThreadPoolExecutor(WORKERS) as pool:
|
| 98 |
+
pres = list(pool.map(pred_job, pred_sample))
|
| 99 |
+
n_p = len(pres)
|
| 100 |
+
rerun = sum(a for a, _, _ in pres)
|
| 101 |
+
gold = sum(b for _, b, _ in pres)
|
| 102 |
+
bare = sum(c for _, _, c in pres)
|
| 103 |
+
p_ok = rerun == gold == bare == n_p
|
| 104 |
+
print(f"[predict] sample={n_p} re-executed_match={rerun}/{n_p} gold_completion_scores={gold}/{n_p} "
|
| 105 |
+
f"bare_answer_scores={bare}/{n_p} -> {'OK' if p_ok else 'FAIL'}")
|
| 106 |
+
ok_all &= p_ok
|
| 107 |
+
|
| 108 |
+
# 4. negative control
|
| 109 |
+
neg_items = rng.sample(code_ex, N_NEG // 2) + rng.sample(pred_ex, N_NEG // 2)
|
| 110 |
+
pairs = [] # pair each item with a completion from a different generator (drawn serially: rng not thread-safe)
|
| 111 |
+
for x in neg_items:
|
| 112 |
+
pool_ = code_tr if x["kind"] in CODE_KINDS else pred_tr
|
| 113 |
+
while True:
|
| 114 |
+
y = pool_[rng.randrange(len(pool_))]
|
| 115 |
+
if y["template"].split("#")[0] != x["template"].split("#")[0]:
|
| 116 |
+
pairs.append((x, y))
|
| 117 |
+
break
|
| 118 |
+
with ThreadPoolExecutor(WORKERS) as pool:
|
| 119 |
+
negs = list(pool.map(lambda xy: score(xy[1]["completion"], xy[0], timeout=5.0), pairs))
|
| 120 |
+
neg_rate = 100 * sum(negs) / len(negs)
|
| 121 |
+
n_ok = neg_rate < 5
|
| 122 |
+
print(f"[negative] other-item completions scored correct: {sum(negs)}/{len(negs)} ({neg_rate:.1f}%, must be <5%) "
|
| 123 |
+
f"-> {'OK' if n_ok else 'FAIL'}")
|
| 124 |
+
ok_all &= n_ok
|
| 125 |
+
|
| 126 |
+
# 5. leakage
|
| 127 |
+
def sets(items):
|
| 128 |
+
ps = [x["prompt"] for x in items]
|
| 129 |
+
qs = [question_of(p) for p in ps]
|
| 130 |
+
return {"exact": set(ps), "norm": {norm(p) for p in ps}, "qnorm": {norm(q) for q in qs},
|
| 131 |
+
"qhash": {hashlib.sha1(q.encode("utf-8")).hexdigest()[:16] for q in qs},
|
| 132 |
+
"code": {code_norm(x.get("code") or x.get("reference")) for x in items}}
|
| 133 |
+
A, B = sets(tr), sets(ex)
|
| 134 |
+
leak = {k: len(A[k] & B[k]) for k in A}
|
| 135 |
+
total = sum(leak.values())
|
| 136 |
+
l_ok = total == 0
|
| 137 |
+
print(f"[leakage] train_vs_exam {leak} LEAKAGE={total} -> {'OK' if l_ok else 'FAIL'}")
|
| 138 |
+
ok_all &= l_ok
|
| 139 |
+
|
| 140 |
+
print(f"CHECK_A11 {'PASS' if ok_all else 'FAIL'} ({time.time() - t0:.0f}s)")
|
| 141 |
+
return 0 if ok_all else 1
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
if __name__ == "__main__":
|
| 145 |
+
sys.exit(main())
|
tools/packet_a11_build.log
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
A11 code | seed=11 | generators=27 | phrasings train=0,1 exam=2 | python=3.11.9
|
| 2 |
+
train=6021 exam=1026
|
| 3 |
+
train by kind {'complete_function': 669, 'fix_bug': 669, 'predict_output': 2230, 'write_function': 2453}
|
| 4 |
+
exam by kind {'complete_function': 114, 'fix_bug': 114, 'predict_output': 380, 'write_function': 418}
|
| 5 |
+
train by topic {'arabic_text': 669, 'dict': 446, 'for_loop': 223, 'functions': 223, 'list_comprehension': 223, 'list_slicing': 223, 'lists': 892, 'loops': 669, 'math': 892, 'recursion': 446, 'sorting': 223, 'strings': 669, 'while_loop': 223}
|
| 6 |
+
exam by topic {'arabic_text': 114, 'dict': 76, 'for_loop': 38, 'functions': 38, 'list_comprehension': 38, 'list_slicing': 38, 'lists': 152, 'loops': 114, 'math': 152, 'recursion': 76, 'sorting': 38, 'strings': 114, 'while_loop': 38}
|
| 7 |
+
verified in subprocess: {'predict_output': 2610, 'write_function': 2871, 'fix_bug': 783, 'complete_function': 783} | fails=0 | fix_bug buggy-versions all fail tests | verify_time=57s
|
| 8 |
+
leakage train_vs_exam {'exact': 0, 'norm': 0, 'qnorm': 0, 'qhash': 0, 'code': 0, 'param_combos': 0} | train_internal_dups=0
|
| 9 |
+
LEAKAGE=0
|
| 10 |
+
packet_a11_train sha256[:16]=d86d803b10164879 | packet_a11_exam sha256[:16]=4e67493be484b603
|