File size: 8,851 Bytes
db4f3b7 | 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 | #!/usr/bin/env python3
"""Validate this release directory and upload it to a Hugging Face dataset repository."""
from __future__ import annotations
import argparse
import hashlib
import json
import re
from collections import Counter
from pathlib import Path
from typing import Any
_SPLITS = ("train", "validation", "test")
_SCHEMA = ["id", "messages", "tools"]
_UPLOAD_FILES = (
"README.md",
"manifest.json",
"train.jsonl",
"validation.jsonl",
"test.jsonl",
"push_to_hub.py",
"requirements.txt",
)
_DEFAULT_RELEASE_DIR = Path(__file__).resolve().parent
def _read_object(path: Path) -> dict[str, Any]:
value = json.loads(path.read_text(encoding="utf-8"))
if not isinstance(value, dict):
raise ValueError(f"JSON nesnesi bekleniyordu: {path}")
return value
def _validate_message_shape(record_id: str, messages: object, tools: object) -> None:
if not isinstance(messages, list) or len(messages) < 2:
raise ValueError(f"{record_id}: messages en az iki öğe içermeli")
if not isinstance(tools, list):
raise ValueError(f"{record_id}: tools dizi olmalı")
offered: set[str] = set()
for tool in tools:
if not isinstance(tool, dict) or tool.get("type") != "function":
raise ValueError(f"{record_id}: geçersiz tool tanımı")
function = tool.get("function")
if not isinstance(function, dict) or not isinstance(function.get("name"), str):
raise ValueError(f"{record_id}: tool function/name eksik")
offered.add(function["name"])
seen_call_ids: set[str] = set()
has_user = False
for message in messages:
if not isinstance(message, dict):
raise ValueError(f"{record_id}: message nesne olmalı")
role = message.get("role")
if role not in {"system", "user", "assistant", "tool"}:
raise ValueError(f"{record_id}: geçersiz message role: {role}")
has_user = has_user or role == "user"
for call in message.get("tool_calls") or []:
function = call.get("function") if isinstance(call, dict) else None
if not isinstance(function, dict) or function.get("name") not in offered:
raise ValueError(f"{record_id}: sunulmayan tool çağrısı")
if not isinstance(function.get("arguments", {}), dict):
raise ValueError(f"{record_id}: tool arguments nesne olmalı")
call_id = call.get("id")
if call_id:
if call_id in seen_call_ids:
raise ValueError(f"{record_id}: yinelenen tool call id: {call_id}")
seen_call_ids.add(call_id)
if role == "tool" and message.get("tool_call_id") not in seen_call_ids:
raise ValueError(f"{record_id}: bilinmeyen tool_call_id sonucu")
if not has_user:
raise ValueError(f"{record_id}: user mesajı yok")
if messages[-1].get("role") != "assistant":
raise ValueError(f"{record_id}: son mesaj assistant olmalı")
def _format_count(value: int) -> str:
return f"{value:,}".replace(",", ".")
def _validate_readme(readme: str, counts: dict[str, int], behavior_counts: Counter[str]) -> None:
labels = {"train": "Eğitim", "validation": "Doğrulama", "test": "Test"}
for split, label in labels.items():
row = f"| {label} | {_format_count(counts[split])} |"
if row not in readme:
raise ValueError(f"README veri bölümü sayısı güncel değil: {row}")
total_match = re.search(r"\|\s*\*\*Toplam\*\*\s*\|\s*\*\*([^*]+)\*\*\s*\|", readme)
expected_total = _format_count(sum(counts.values()))
if total_match and total_match.group(1).strip() != expected_total:
raise ValueError(f"README toplam sayısı güncel değil: {expected_total}")
for behavior, count in behavior_counts.items():
pattern = (
rf"\|\s*[^|\n]+\s*\|\s*`{re.escape(behavior)}`\s*\|\s*"
rf"{_format_count(count)}\s*\|"
)
if not re.search(pattern, readme):
raise ValueError(
f"README davranış sayısı güncel değil: {behavior}={_format_count(count)}"
)
def validate_release(release_dir: Path) -> dict[str, Any]:
"""Fail closed before any network request."""
missing = [name for name in _UPLOAD_FILES if not (release_dir / name).is_file()]
if missing:
raise FileNotFoundError(f"Eksik yayın dosyaları: {', '.join(missing)}")
manifest = _read_object(release_dir / "manifest.json")
if manifest.get("schema") != _SCHEMA:
raise ValueError(f"Manifest şeması tam olarak {_SCHEMA} olmalı")
expected_counts = manifest.get("counts")
if not isinstance(expected_counts, dict) or set(expected_counts) != set(_SPLITS):
raise ValueError(f"Manifest counts yalnızca {_SPLITS} splitlerini içermeli")
seen_ids: set[str] = set()
actual_counts: dict[str, int] = {}
hashes: dict[str, str] = {}
behavior_counts: Counter[str] = Counter()
for split in _SPLITS:
path = release_dir / f"{split}.jsonl"
digest = hashlib.sha256()
count = 0
with path.open("rb") as stream:
for line_number, raw_line in enumerate(stream, start=1):
digest.update(raw_line)
if not raw_line.strip():
raise ValueError(f"{path}:{line_number}: boş satır")
row = json.loads(raw_line)
if not isinstance(row, dict) or list(row) != _SCHEMA:
raise ValueError(f"{path}:{line_number}: alanlar tam olarak {_SCHEMA} olmalı")
record_id = row["id"]
if not isinstance(record_id, str) or not record_id.startswith("TRFIN-"):
raise ValueError(f"{path}:{line_number}: geçersiz id")
if record_id in seen_ids:
raise ValueError(f"Splitler arasında yinelenen id: {record_id}")
seen_ids.add(record_id)
behavior = record_id.removeprefix("TRFIN-").rsplit("-", 1)[0]
behavior_counts[behavior] += 1
_validate_message_shape(record_id, row["messages"], row["tools"])
count += 1
actual_counts[split] = count
hashes[path.name] = digest.hexdigest()
if actual_counts != expected_counts:
raise ValueError(
f"Manifest sayıları uyuşmuyor: expected={expected_counts}, actual={actual_counts}"
)
_validate_readme(
(release_dir / "README.md").read_text(encoding="utf-8"),
actual_counts,
behavior_counts,
)
return {
"counts": actual_counts,
"total": sum(actual_counts.values()),
"sha256": hashes,
"behaviors": dict(sorted(behavior_counts.items())),
}
def push(
repo_id: str,
release_dir: Path,
*,
revision: str,
private: bool,
commit_message: str,
dry_run: bool,
) -> dict[str, Any]:
validation = validate_release(release_dir)
summary = {
"repo_id": repo_id,
"revision": revision,
"private": private,
"files": list(_UPLOAD_FILES),
**validation,
}
if dry_run:
return {"dry_run": True, **summary}
try:
from huggingface_hub import HfApi
except ImportError as error:
raise RuntimeError(
'Yükleme için `pip install "huggingface-hub>=0.26"` çalıştırın'
) from error
api = HfApi()
api.create_repo(repo_id=repo_id, repo_type="dataset", private=private, exist_ok=True)
commit = api.upload_folder(
repo_id=repo_id,
repo_type="dataset",
folder_path=release_dir,
revision=revision,
commit_message=commit_message,
allow_patterns=list(_UPLOAD_FILES),
)
return {"dry_run": False, "commit": str(commit), **summary}
def main() -> int:
parser = argparse.ArgumentParser(
description="Finetool-TR yayın klasörünü doğrula ve Hugging Face'e yükle"
)
parser.add_argument("--repo-id", required=True, help="Örnek: kullanici/finetool-tr")
parser.add_argument("--release-dir", type=Path, default=_DEFAULT_RELEASE_DIR)
parser.add_argument("--revision", default="main")
parser.add_argument("--private", action="store_true")
parser.add_argument("--commit-message", default="FintoolDataset-TR doğrulanmış veri sürümü")
parser.add_argument("--dry-run", action="store_true")
args = parser.parse_args()
result = push(
args.repo_id,
args.release_dir.resolve(),
revision=args.revision,
private=args.private,
commit_message=args.commit_message,
dry_run=args.dry_run,
)
print(json.dumps(result, ensure_ascii=False, indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main())
|