File size: 9,798 Bytes
cd3dde0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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', '<unknown>')}")
    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 = "<unknown>") -> 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]