"""MiniClef-4B preprocessing. Converts raw Open-Jev rows into unified internal representation: { "state": {"text": str, "images": [...], "videos": [...], "metadata": {...}}, "schema": {"questions": [{"id": str, "type": str, "question": str, "choices": [str,...], "kind": str}]}, "labels": {question_id: [float,...]} } Robustness: fails clearly on missing fields, unsupported types, malformed labels, empty choices, invalid alignment. Never silently discards. """ from __future__ import annotations import json from typing import Any, Dict, List # Open-Jev kinds observed in the wild. Mapping to internal decision types: # choice -> categorical (variable K, soft distribution allowed) # noul -> boolean (always 2 options ['no','yes'] in release-v2, treated as categorical K=2) # score -> ordinal/score/distribution (ordered options, distribution labels) SUPPORTED_KINDS = {"choice", "noul", "score"} # Internal type names exposed in schema (kept extensible, not hard-coded classifiers) KIND_TO_TYPE = { "choice": "categorical", "noul": "boolean", "score": "ordinal", } REQUIRED_ROW_FIELDS = ["id", "group_id", "split", "source", "kind", "question", "options", "target", "state_json"] def validate_row(row: Dict[str, Any]) -> None: """Raise ValueError with clear message if row is invalid.""" for f in REQUIRED_ROW_FIELDS: if f not in row or row[f] is None: raise ValueError(f"dataset field missing: '{f}' in row id={row.get('id', '')}") kind = row["kind"] if kind not in SUPPORTED_KINDS: raise ValueError( f"unsupported decision type: kind='{kind}' id={row.get('id')}. " f"Supported kinds: {sorted(SUPPORTED_KINDS)}" ) options = row["options"] if not isinstance(options, (list, tuple)) or len(options) == 0: raise ValueError(f"question choices are empty: id={row.get('id')} kind={kind}") for i, o in enumerate(options): if not isinstance(o, str) or len(o.strip()) == 0: raise ValueError(f"malformed choice at index {i}: id={row.get('id')} choice={o!r}") target = row["target"] if not isinstance(target, (list, tuple)): raise ValueError(f"labels are malformed (target not a list): id={row.get('id')} target={target!r}") if len(target) != len(options): raise ValueError( f"state/question alignment is invalid: len(target)={len(target)} != " f"len(options)={len(options)} id={row.get('id')}" ) for i, v in enumerate(target): if not isinstance(v, (int, float)): raise ValueError(f"labels are malformed (non-numeric at {i}): id={row.get('id')} target={target!r}") if v < -1e-6 or v > 1.0 + 1e-6: raise ValueError(f"labels are malformed (out of [0,1] at {i}): id={row.get('id')} target={target!r}") s = float(sum(target)) if abs(s - 1.0) > 1e-3: raise ValueError( f"labels are malformed (target must sum to 1.0, got {s}): id={row.get('id')} target={target!r}" ) if not isinstance(row["question"], str) or len(row["question"].strip()) == 0: raise ValueError(f"dataset field missing/empty: 'question' id={row.get('id')}") if not isinstance(row["state_json"], str) or len(row["state_json"]) == 0: raise ValueError(f"dataset field missing/empty: 'state_json' id={row.get('id')}") def decode_state(state_json: str, row_id: str = "") -> Dict[str, Any]: """Decode state_json which may be a plain string or a JSON object. Returns dict with keys: text, images, videos, raw, structured. Multimodal-ready: if structured state contains image/video keys, they are extracted into images/videos lists (else empty). Text is always produced. """ if not isinstance(state_json, str): raise ValueError(f"labels are malformed: state_json not a string id={row_id}") s = state_json.strip() if len(s) == 0: raise ValueError(f"dataset field missing/empty: decoded state is empty id={row_id}") # Try JSON decode. Plain conversation strings will fail -> treated as text. try: obj = json.loads(s) except (json.JSONDecodeError, ValueError): return {"text": s, "images": [], "videos": [], "raw": s, "structured": None} # JSON succeeded if isinstance(obj, str): if len(obj.strip()) == 0: raise ValueError(f"dataset field missing/empty: decoded state is empty id={row_id}") return {"text": obj, "images": [], "videos": [], "raw": s, "structured": None} if isinstance(obj, dict): images: List[Any] = [] videos: List[Any] = [] # Future multimodal: extract known media keys if present for k in ("images", "image", "pictures", "figures"): if k in obj and obj[k] is not None: v = obj[k] if isinstance(v, list): images.extend(v) else: images.append(v) for k in ("videos", "video", "clips"): if k in obj and obj[k] is not None: v = obj[k] if isinstance(v, list): videos.extend(v) else: videos.append(v) text = state_to_text(obj) return {"text": text, "images": images, "videos": videos, "raw": s, "structured": obj} # JSON list / number etc -> serialize deterministically as text return {"text": json.dumps(obj, ensure_ascii=False, sort_keys=True), "images": [], "videos": [], "raw": s, "structured": obj} def state_to_text(state_obj: Any) -> str: """Deterministic conversion of structured state to text for the backbone. If dict has obvious text fields, prefer them; else stable JSON dump. Never hard-codes specific task questions. """ if isinstance(state_obj, str): return state_obj if isinstance(state_obj, dict): # Common single-text wrappers for k in ("text", "conversation", "body", "content", "passage", "document"): if k in state_obj and isinstance(state_obj[k], str) and state_obj[k].strip(): # Still include full context to avoid information loss: # return full stable dump (keeps all fields), not just one field. break return json.dumps(state_obj, ensure_ascii=False, sort_keys=True) return json.dumps(state_obj, ensure_ascii=False, sort_keys=True) def question_id_from_row(row: Dict[str, Any]) -> str: """Derive stable question id: last ':' segment of row id, fallback to question hash.""" rid = str(row.get("id", "")) if ":" in rid: return rid.rsplit(":", 1)[-1] return rid or "q0" def rows_to_grouped_state(rows: List[Dict[str, Any]]) -> Dict[str, Any]: """Convert list of rows sharing one group_id into unified representation. Raises on: empty input, mixed group_id/state, invalid rows. Preserves relationship between multiple questions of the same state. """ if len(rows) == 0: raise ValueError("state/question alignment is invalid: empty group") group_ids = {r.get("group_id") for r in rows} if len(group_ids) != 1: raise ValueError(f"state/question alignment is invalid: mixed group_id {group_ids}") group_id = next(iter(group_ids)) # Validate every row first (fail clearly, don't discard) for r in rows: validate_row(r) # All rows in a group should share the same underlying state. states = {r["state_json"] for r in rows} if len(states) != 1: raise ValueError( f"state/question alignment is invalid: group {group_id} has " f"{len(states)} distinct state_json values" ) state = decode_state(rows[0]["state_json"], row_id=rows[0].get("id", group_id)) questions: List[Dict[str, Any]] = [] labels: Dict[str, List[float]] = {} seen_qids = set() for r in rows: qid = question_id_from_row(r) if qid in seen_qids: raise ValueError(f"state/question alignment is invalid: duplicate question id '{qid}' in group {group_id}") seen_qids.add(qid) qtype = KIND_TO_TYPE[r["kind"]] questions.append( { "id": qid, "type": qtype, "kind": r["kind"], "question": r["question"], "choices": list(r["options"]), "source": r.get("source", ""), "row_id": r.get("id", ""), } ) labels[qid] = [float(v) for v in r["target"]] # Sort questions by id for determinism questions = sorted(questions, key=lambda q: q["id"]) return { "group_id": group_id, "state": state, "schema": {"questions": questions}, "labels": labels, "split": rows[0].get("split", ""), } def build_option_text(state_text: str, question: str, option: str, kind: str) -> str: """Build single backbone input text for (state, question, one candidate option). Generic template — no hard-coded question content. V0 text-only path. Multimodal inputs (images/videos) are passed separately to the processor. """ # Keep template short to save sequence length; option scoring needs full context. return ( f"State: {state_text}\n" f"Question: {question}\n" f"Option: {option}\n" f"Decision:" ) def example_to_model_inputs( state_text: str, question: str, options: List[str], kind: str ) -> List[str]: """Expand one question into K option-conditioned texts (dynamic K).""" if len(options) == 0: raise ValueError("question choices are empty: cannot build model inputs") return [build_option_text(state_text, question, o, kind) for o in options]