| |
| |
| |
| """Normalize approved Hub sources into auditable private training candidates.""" |
|
|
| from __future__ import annotations |
|
|
| from datetime import UTC, datetime |
| import hashlib |
| import json |
| import os |
| import re |
| from typing import Any |
|
|
| SECRET = re.compile(r"(?:\bsk-[A-Za-z0-9_-]{12,}|\bhf_[A-Za-z0-9]{12,})") |
|
|
|
|
| def deterministic_split(example_id: str) -> str: |
| value = int(hashlib.sha256(example_id.encode()).hexdigest()[:8], 16) % 100 |
| return "train" if value < 80 else "validation" if value < 90 else "test" |
|
|
|
|
| def _base_record( |
| *, example_id: str, task_type: str, input_text: str, target: str, |
| source_id: str, source_revision: str, license_spdx: str, |
| status: str, evaluators: list[str], evaluation: dict[str, Any], |
| ) -> dict[str, Any]: |
| return { |
| "example_id": example_id, |
| "split": deterministic_split(example_id), |
| "task_type": task_type, |
| "input": input_text.strip(), |
| "target": target.strip(), |
| "scope": {"tenant": "public-source", "project": "orchestra-q", "user": None, "privacy_class": "internal"}, |
| "provenance": { |
| "source_type": "huggingface_dataset", |
| "source_refs": [f"hf://datasets/{source_id}@{source_revision}"], |
| "collected_at": datetime.now(UTC).isoformat(), |
| "collector": "orchestra-q-hf-curator-v1", |
| }, |
| "license": {"spdx": license_spdx, "compatible": True, "restrictions": []}, |
| "redaction": {"status": "not_required", "policy_version": "secret-redaction-v1"}, |
| "quality": {"verification_status": status, "evaluator_versions": evaluators}, |
| "evaluation": evaluation, |
| } |
|
|
|
|
| def normalize_row( |
| row: dict[str, Any], *, adapter: str, source_id: str, |
| source_revision: str, license_spdx: str, |
| ) -> list[dict[str, Any]]: |
| if adapter == "openr1_math": |
| generations = row.get("generations") or [] |
| math_ok = row.get("correctness_math_verify") or [] |
| judge_ok = row.get("correctness_llama") or [] |
| complete = row.get("is_reasoning_complete") or [] |
| for index, generation in enumerate(generations): |
| verified = bool(index < len(math_ok) and math_ok[index]) or bool(index < len(judge_ok) and judge_ok[index]) |
| complete_ok = index >= len(complete) or complete[index] is True |
| if verified and complete_ok and isinstance(generation, str) and generation.strip(): |
| example_id = f"{row.get('uuid') or hashlib.sha256(str(row.get('problem')).encode()).hexdigest()}:{index}" |
| return [_base_record( |
| example_id=example_id, task_type="mathematical_reasoning", |
| input_text=str(row.get("problem") or ""), target=generation, |
| source_id=source_id, source_revision=source_revision, |
| license_spdx=license_spdx, status="verified", |
| evaluators=["math_verify" if index < len(math_ok) and math_ok[index] else "llama_judge"], |
| evaluation={"reference_answer": str(row.get("answer") or ""), "verifier": "source_correctness_metadata"}, |
| )] |
| return [] |
| if adapter == "text2cadquery": |
| prompt, response = row.get("prompt"), row.get("response") |
| if not isinstance(prompt, str) or not isinstance(response, str) or not prompt.strip() or not response.strip(): |
| return [] |
| example_id = hashlib.sha256((prompt + "\0" + response).encode()).hexdigest() |
| return [_base_record( |
| example_id=example_id, task_type="text_to_cadquery", input_text=prompt, |
| target=response, source_id=source_id, source_revision=source_revision, |
| license_spdx=license_spdx, status="partial", evaluators=["structural_only"], |
| evaluation={"verifier": "cadquery_sandbox_required"}, |
| )] |
| if adapter == "agent_trace": |
| conversations = row.get("conversations") |
| if not isinstance(conversations, list) or not conversations: |
| return [] |
| verifier = str(row.get("verifier_output") or row.get("judgment") or row.get("result") or "") |
| positive = any(token in verifier.casefold() for token in ("pass", "success", "correct", "reward: 1")) |
| if not positive: |
| return [] |
| instruction = row.get("instruction") or next((m.get("content") for m in conversations if isinstance(m, dict) and m.get("role") == "user"), None) |
| if not isinstance(instruction, str): |
| return [] |
| target = json.dumps(conversations, ensure_ascii=False, sort_keys=True) |
| example_id = str(row.get("run_id") or hashlib.sha256((instruction + target).encode()).hexdigest()) |
| return [_base_record( |
| example_id=example_id, task_type="agent_trace", input_text=instruction, |
| target=target, source_id=source_id, source_revision=source_revision, |
| license_spdx=license_spdx, status="verified", evaluators=["source_environment_outcome"], |
| evaluation={"verifier": "source_outcome", "source": row.get("original_source")}, |
| )] |
| raise ValueError(f"unsupported adapter: {adapter}") |
|
|
|
|
| def main() -> None: |
| from datasets import Dataset, DatasetDict, load_dataset |
|
|
| source_id = os.environ["SOURCE_ID"] |
| repo = os.environ["SOURCE_REPO"] |
| revision = os.environ["SOURCE_REVISION"] |
| config = os.getenv("SOURCE_CONFIG") or None |
| split = os.getenv("SOURCE_SPLIT", "train") |
| adapter = os.environ["ADAPTER"] |
| license_spdx = os.environ["LICENSE_SPDX"] |
| max_rows = int(os.getenv("MAX_ROWS", "100000")) |
| output_repo = os.environ["OUTPUT_REPO"] |
|
|
| source = load_dataset(repo, config, split=split, revision=revision, streaming=True) |
| records: list[dict[str, Any]] = [] |
| seen_inputs: set[str] = set() |
| rejected_secrets = 0 |
| for row in source.take(max_rows): |
| for record in normalize_row(row, adapter=adapter, source_id=source_id, source_revision=revision, license_spdx=license_spdx): |
| serialized = json.dumps(record, ensure_ascii=False, sort_keys=True) |
| if SECRET.search(serialized): |
| rejected_secrets += 1 |
| continue |
| fingerprint = hashlib.sha256(record["input"].strip().casefold().encode()).hexdigest() |
| if fingerprint in seen_inputs: |
| continue |
| seen_inputs.add(fingerprint) |
| records.append(record) |
|
|
| grouped = {name: [r for r in records if r["split"] == name] for name in ("train", "validation", "test")} |
| dataset = DatasetDict({name: Dataset.from_list(rows) for name, rows in grouped.items() if rows}) |
| dataset.push_to_hub(output_repo, private=True, commit_message=f"Curate {source_id}@{revision[:12]}") |
| print(json.dumps({"source": source_id, "accepted": len(records), "rejected_secrets": rejected_secrets, "splits": {k: len(v) for k, v in grouped.items()}, "output_repo": output_repo}, sort_keys=True)) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|