zbynka-dataset / generation /validate_dataset.py
nekam13's picture
Add files using upload-large-folder tool
c3c4f0d verified
Raw
History Blame Contribute Delete
9.05 kB
#!/usr/bin/env python3
"""Streaming integrity and content checks for the expansion.
This is intentionally independent of the writers' in-memory uniqueness checks:
it reads the files that will actually be uploaded.
"""
from __future__ import annotations
import csv
import hashlib
import json
import re
from collections import Counter
from pathlib import Path
from common import REPO, OUT, text_sha256
from generate_creative import RHYME_PAIRS, digits
EXPECTED = {
"common_sense_v2.csv": 100_000,
"small_talk_v2.csv": 10_000,
"wizard_history_v2.csv": 10_000,
"geography_v2.csv": 100_000,
"biology_v2.csv": 100_000,
"social_etiquette_v2.csv": 10_000,
"history_cz_wizard_v2.csv": 100_000,
"cooking_v2.csv": 100_000,
"creative/stories.csv": 25_000,
"creative/essays_and_slohy.csv": 25_000,
"creative/poetry.csv": 20_000,
"creative/songs.csv": 20_000,
"creative/rhyme_craft.csv": 10_000,
"benchmarks/logic.csv": 10_000,
"benchmarks/math.csv": 10_000,
"benchmarks/instruction_following.csv": 10_000,
"benchmarks/truthfulness.csv": 10_000,
"benchmarks/context_reading.csv": 10_000,
"benchmarks/temporal_spatial.csv": 10_000,
"benchmarks/causal_counterfactual.csv": 10_000,
"benchmarks/language.csv": 10_000,
"benchmarks/planning_tools.csv": 10_000,
"benchmarks/code_data.csv": 10_000,
}
TAGS = {
"<|im_start|>system": 1,
"<|im_start|>user": 1,
"<|im_start|>assistant": 1,
"<thought>": 1,
"</thought>": 1,
"<|im_end|>": 3,
}
def last_word(line: str) -> str:
line = line.casefold().strip()
line = re.sub(r"[^a-záčďéěíňóřšťúůýž]+$", "", line)
return line.split()[-1]
def answer_lines(text: str) -> list[str]:
answer = text.split("</thought>\n", 1)[1].rsplit("<|im_end|>", 1)[0]
return answer.splitlines()
def validate_file(rel: str, expected: int, global_hashes: set[bytes]) -> dict:
path = OUT / rel
if not path.exists():
raise AssertionError(f"Missing {rel}")
count = 0
unique = set()
min_len = 10**9
max_len = 0
total_len = 0
forbidden = 0
tag_errors = 0
with path.open("r", encoding="utf-8", newline="") as f:
reader = csv.DictReader(f)
if reader.fieldnames != ["text"]:
raise AssertionError(f"{rel}: expected one text column, got {reader.fieldnames}")
for row in reader:
count += 1
text = row["text"]
digest = hashlib.blake2b(text.encode("utf-8"), digest_size=16).digest()
if digest in unique:
raise AssertionError(f"{rel}: duplicate row {count}")
unique.add(digest)
# Cross-file duplicates are also undesirable; a repeated exact
# conversation should not silently inflate the training mix.
if digest in global_hashes:
raise AssertionError(f"cross-file duplicate at {rel}:{count}")
global_hashes.add(digest)
for tag, n in TAGS.items():
if text.count(tag) != n:
tag_errors += 1
raise AssertionError(f"{rel}:{count}: malformed ChatML tag {tag}")
if "\x00" in text:
raise AssertionError(f"{rel}:{count}: NUL byte")
if rel in {"wizard_history_v2.csv", "history_cz_wizard_v2.csv"} and "magi" in text.casefold():
forbidden += 1
raise AssertionError(f"{rel}:{count}: forbidden word root")
n = len(text)
min_len = min(min_len, n); max_len = max(max_len, n); total_len += n
if count != expected:
raise AssertionError(f"{rel}: expected {expected}, got {count}")
return {
"path": f"data/additions/{rel}",
"rows": count,
"bytes": path.stat().st_size,
"sha256": text_sha256(path),
"unique_rows": len(unique),
"min_chars": min_len,
"max_chars": max_len,
"avg_chars": round(total_len / count, 2),
"tag_errors": tag_errors,
"forbidden_hits": forbidden,
}
def validate_rhymes() -> dict:
checks = {"poetry_rows": 0, "song_rows": 0, "poetry_bad": 0, "song_bad": 0}
p = OUT / "creative/poetry.csv"
with p.open(encoding="utf-8", newline="") as f:
for i, row in enumerate(csv.DictReader(f)):
lines = answer_lines(row["text"])[1:]
e, a, b, c, raw_d = digits(i, [2, 25, 10, 30, 30])
d = (raw_d * 13 + a * 7 + b * 3 + c + 1) % 30
pa, pb = RHYME_PAIRS[c], RHYME_PAIRS[d]
expected = [pa[0], pa[1], pb[0], pb[1]] if e == 0 else [pa[0], pb[0], pa[1], pb[1]]
checks["poetry_rows"] += 1
if [last_word(x) for x in lines] != expected:
checks["poetry_bad"] += 1
p = OUT / "creative/songs.csv"
with p.open(encoding="utf-8", newline="") as f:
for i, row in enumerate(csv.DictReader(f)):
lines = [x for x in answer_lines(row["text"]) if x and not x.startswith("**")]
e, a, b, c = digits(i, [10, 25, 10, 30])
d = (a * 11 + b * 5 + c * 7 + e + 3) % 30
pa, pb = RHYME_PAIRS[c], RHYME_PAIRS[d]
expected = [pa[0], pa[1], pb[0], pb[1], pb[0], pa[0], pb[1], pa[1]]
checks["song_rows"] += 1
if [last_word(x) for x in lines] != expected:
checks["song_bad"] += 1
if checks["poetry_bad"] or checks["song_bad"]:
raise AssertionError(f"Rhyme validation failed: {checks}")
return checks
def legacy_report() -> dict:
result = {}
for path in sorted(REPO.glob("*.csv")):
rows = 0; malformed = 0
try:
with path.open(encoding="utf-8-sig", newline="") as f:
for row in csv.DictReader(f):
rows += 1
text = row.get("text", "")
if any(text.count(tag) != n for tag, n in TAGS.items()):
malformed += 1
except Exception as exc:
result[path.name] = {"error": repr(exc)}
continue
result[path.name] = {"rows": rows, "malformed_chatml_rows": malformed, "bytes": path.stat().st_size}
return result
def main() -> None:
global_hashes: set[bytes] = set()
files = [validate_file(rel, n, global_hashes) for rel, n in EXPECTED.items()]
rhyme = validate_rhymes()
additional_rows = sum(x["rows"] for x in files)
additional_bytes = sum(x["bytes"] for x in files)
manifest = {
"generated_at": "2026-07-30",
"repository": "nekam13/zbynka-dataset",
"language": "cs",
"schema": {"format": "CSV", "columns": ["text"], "conversation": "ChatML-like text with concise thought summary"},
"purpose": "Additional thematic expansion; original repository files are retained.",
"additional_rows": additional_rows,
"additional_bytes": additional_bytes,
"additional_mib": round(additional_bytes / 2**20, 2),
"files": files,
"rhyme_validation": rhyme,
"global_exact_duplicate_count": 0,
"legacy_root_report": legacy_report(),
"assumptions": [
"The word 'dalších' was interpreted literally: requested rows were added to, not substituted for, existing files.",
"Cooking was assigned 100,000 additional rows because the request asked to teach cooking but did not specify a count; this is explicitly documented.",
"Benchmark-like items are original synthetic tasks inspired by task families, not copied benchmark questions.",
"The hidden historical layer is intentionally in-universe and is marked separately from publicly documented history.",
],
"quality_notes": [
"Every new file has exact requested row count and exact-row uniqueness, including across new files.",
"Wizard and integrated-history additions contain no case-insensitive 'magi' fragment.",
"Poetry and song rhyme schemes were checked row by row (40,000 rows).",
"Programmatic checks do not replace human review of factual, stylistic, or safety-sensitive content.",
],
"benchmark_inspiration": [
"https://github.com/google/BIG-bench",
"https://github.com/openai/simple-evals",
"https://aclanthology.org/2025.tacl-1.50/",
"https://github.com/MFajcik/benczechmark-leaderboard",
"https://github.com/simecek/MiniCzechBenchmark",
],
"hub_upload_docs": [
"https://huggingface.co/docs/huggingface_hub/guides/upload",
"https://huggingface.co/docs/huggingface_hub/package_reference/hf_api",
],
}
out = REPO / "generation" / "manifest.json"
out.write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(json.dumps({"additional_rows": additional_rows, "additional_mib": manifest["additional_mib"], "files": len(files), "rhyme": rhyme}, ensure_ascii=False))
if __name__ == "__main__":
main()