FintoolDataset-tr / push_to_hub.py
Dbmaxwell's picture
FintoolDataset-TR doğrulanmış veri sürümü
db4f3b7 verified
Raw History Blame Contribute Delete
8.85 kB
#!/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())