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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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
"""Export next-pipeline question packages into an evaluation item set.

Input: one or more ``questions.jsonl`` from np/prover_questions.py (each in
a directory named after its script). Output, in a fresh directory:

- ``items.jsonl``  public: question text, answer form, scorer, video paths
- ``truth.jsonl``  private: ``replay.value`` in the form the scorer compares
- ``export.json``  counts per version and kind, everything skipped and why, and the
  denominator check: PASS rows read = items + skipped PASS rows, else exit 1
- ``maps/``        PNG option images for layout.map_choice items, and the attached PNGs of every other
  row that lists ``presentation.images`` (floor-plan location questions with their A–D markers,
  map scaffolds such as given_grid / given_furniture), copied from the prover output next to the
  question file

Videos are looked up in the batch layout
``<videos>/r/<script_id>/r/observation/videos/<observer>.mp4``, then as
``<videos>/<script_id>/<observer>.mp4``, ``<videos>/<observer>.mp4`` or the release layout
``<videos>/<house>/<script_id>/observation/videos/<observer>.mp4``.
A row's ``recording_views`` (start/end frame per view) set the footage its question seconds refer to:
a view that is not the whole recording is sent as the matching clip from ``--clips``
(clips/index.json), and a crop with no clip is an error rather than a fall-back to the full video.
``--items-from`` keeps only the listed item ids (e.g. a review set's questions.jsonl).
A supplied video root must contain every requested recording. Without
``--videos``, items are written with ``has_video: false`` for a text-only
baseline, and a video run refuses them. Map items need ``--scripts`` (the scene is read from
``<scripts>/<script_id>/script.json``) and ffmpeg with librsvg. A row whose attached PNG is missing
is skipped (``attached image missing``): its question refers to a figure, so it cannot be asked without it.

    python3 tools/evaluation/np_export.py --questions <batch>/*/questions.jsonl \\
        --out runs/eval-items-<date>/ [--videos <render root>] [--scripts <gen root>]
"""
import argparse
import collections
import json
import random
import shutil
import subprocess
import sys
from pathlib import Path

if __package__ in (None, ''):
    sys.path.insert(0, str(Path(__file__).resolve().parent))
    import np_answers  # noqa: E402
else:
    from . import np_answers

ROOT = Path(__file__).resolve().parents[2]

sys.path.insert(0, str(ROOT))
from embodied_pipeline.domain import storage


def find_video(videos, script_id, observer):
    if not videos:
        return None
    root = Path(videos)
    for path in (root / 'r' / script_id / 'r/observation/videos' / f'{observer}.mp4',
                 root / script_id / f'{observer}.mp4', root / f'{observer}.mp4'):
        if path.is_file():
            return path
    # release layout: <videos>/<house>/<script_id>/observation/videos/<observer>.mp4
    hits = sorted(root.glob(f'*/{script_id}/observation/videos/{observer}.mp4'))
    if len(hits) > 1:
        raise FileNotFoundError(f'ambiguous video: script_id={script_id}, observer={observer}: {hits}')
    return hits[0] if hits else None


class ClipError(ValueError):
    """A question shows part of a recording (recording_views) and no matching clip is available."""


def load_clips(clips):
    """Index of frame-exact clips cut from full recordings, keyed (script_id, observer, start, end_exclusive).

    ``clips`` is a clips/index.json (schema np-review-clips/1, as written by tools/evaluation/cut_clips.py or the
    review tools' cut_clips.py), or the directory holding it, or that directory's parent. Each entry's key is the clip
    path relative to the index's parent directory; the entry names ``script_id`` and ``observer``, or else its
    ``source`` ends in <script_id>/observation/videos/<observer>.mp4.
    """
    if not clips:
        return {}
    path = Path(clips)
    for cand in (path, path / 'index.json', path / 'clips' / 'index.json'):
        if cand.is_file():
            path = cand
            break
    else:
        raise FileNotFoundError(f'no clips index under {clips}')
    data = json.loads(path.read_text(encoding='utf-8'))
    if data.get('schema') != 'np-review-clips/1':
        raise ValueError(f'{path}: unexpected clips schema {data.get("schema")!r}')
    if data.get('failed'):
        raise ValueError(f'{path}: {len(data["failed"])} clips failed to cut; re-run the cutter first')
    index = {}
    for rel, c in data['clips'].items():
        src = Path(c['source'])
        if not (c.get('script_id') and c.get('observer')) and src.parent.parts[-2:] != ('observation', 'videos'):
            raise ValueError(f'{path}: clip {rel}: unexpected source layout {src}')
        if c['frames'] != c['end_frame_exclusive'] - c['start_frame']:
            raise ValueError(f'{path}: clip {rel}: {c["frames"]} frames != end - start')
        clip = (path.parent.parent / rel).resolve()
        if not clip.is_file():
            raise FileNotFoundError(f'{path}: clip file missing: {clip}')
        # cut_clips.py names the clip's script and observer; older indexes leave them to the release source path
        key = (c.get('script_id') or src.parent.parent.parent.name, c.get('observer') or src.stem,
               c['start_frame'], c['end_frame_exclusive'])
        index[key] = {'path': clip, 'fps': c.get('fps'), 'sha256': c.get('sha256')}
    return index


def full_frames(path):
    """Frame count of a full recording (decides whether a recording view starting at frame 0 is the whole video)."""
    sys.path.insert(0, str(Path(__file__).resolve().parent))
    import media
    info = media.probe(path)
    return info['frame_count'] if info['frame_count'] is not None else round(info['duration_s'] * info['fps'])


def view_video(row, letter, observer, script_id, videos, clips):
    """Video entry for one view: the full recording, or the clip named by the row's recording_views.

    Question seconds are local to the recording view, so a cropped view must go out as its clip; a crop
    without a matching clip is an error, never a silent fallback to the full recording.
    """
    path = find_video(videos, script_id, observer)
    if path is None:
        return None
    rv = (row.get('recording_views') or {}).get(letter)
    if rv is None:
        return {'view': letter, 'path': str(Path(path).resolve())}
    if rv.get('observer') != observer:
        raise ClipError(f'recording_views[{letter}] observer {rv.get("observer")!r} != presentation {observer!r} '
                        f'(script_id={script_id})')
    a, b = rv['start_frame'], rv['end_frame_exclusive']
    clip = clips.get((script_id, observer, a, b))
    if clip is None and a == 0 and full_frames(path) == b:
        return {'view': letter, 'path': str(Path(path).resolve())}
    if clip is None:
        raise ClipError(f'no clip for cropped view: script_id={script_id}, view={letter}, observer={observer}, '
                        f'frames {a}-{b} (pass --clips with an index that has it)')
    return {'view': letter, 'path': str(clip['path']),
            'clip': {'source': str(Path(path).resolve()), 'start_frame': a, 'end_frame_exclusive': b,
                     'fps': clip['fps'], 'sha256': clip['sha256']}}


def render_maps(row, spec, scripts, script_id, out):
    """Write one PNG per option image; returns [{'label', 'path'}] relative to ``out``."""
    if not scripts:
        raise np_answers.AnswerError('map item needs --scripts for the scene')
    script = Path(scripts) / script_id / 'script.json'
    if not script.is_file():
        raise np_answers.AnswerError(f'map item: {script} not found')
    if not shutil.which('ffmpeg'):
        raise np_answers.AnswerError('map item: ffmpeg is required to rasterise the SVG')
    sys.path.insert(0, str(ROOT))
    try:
        from embodied_pipeline.prover import map_svg
    finally:
        sys.path.remove(str(ROOT))
    scene = json.loads(script.read_text(encoding='utf-8'))['scene']
    _, slot = np_answers.reply_slot(row)
    value = slot['value']
    target = out / 'maps' / script_id / row['candidate_id'].replace('/', '__').replace('#', '_')
    target.mkdir(parents=True, exist_ok=True)
    images = []
    for option in spec['options']:
        letter = option['id']
        svg = map_svg.render(value['layouts'][letter], scene, label=value.get('labels') or (),
                             furniture=value.get('furniture') or ())
        (target / f'{letter}.svg').write_text(svg, encoding='utf-8')
        png = target / f'{letter}.png'
        subprocess.run(['ffmpeg', '-v', 'error', '-y', '-i', str(target / f'{letter}.svg'), str(png)], check=True)
        images.append({'label': letter, 'caption': option, 'path': str(png.relative_to(out))})
    return images


def item_of(row, script_id, out, videos=None, scripts=None, clips=None, source_dir=None):
    """(public item, private truth) for one package row."""
    vid = row['public']['version_id']
    spec = np_answers.public_form(row)
    kind = spec['type'][3:]
    scorer, source = np_answers.scorer(vid, kind)
    item_id = f"{script_id}/{row['candidate_id']}"
    letters = row['scope']['videos']
    route = row['presentation']['videos']
    views, missing = [], []
    for letter in letters:
        view = view_video(row, letter, route[letter], script_id, videos, clips or {})
        if view is None:
            if videos is not None:
                raise FileNotFoundError(
                    f'missing video: script_id={script_id}, observer={route[letter]}, '
                    f'view={letter}, videos={videos}')
            missing.append(letter)
        else:
            views.append(view)
    text = ''.join(seg['text'] for seg in row['public']['text']['zh'])
    question = {'zh': text}
    if 'en' in row['public']['text']:
        question['en'] = ''.join(seg['text'] for seg in row['public']['text']['en'])
    item = {'item_id': item_id, 'version_id': vid, 'question': question, 'answer': spec,
            'scoring': {**scorer, 'answer_type': kind, 'source': source},
            'videos': views,
            'tags': {'script_id': script_id, 'family': vid.split('.')[0], 'form': vid.split('/')[0],
                     'views': 'multi_ego' if '/multi_ego' in vid else 'single_ego', 'answer_kind': kind,
                     'has_video': not missing, 'video_letters': letters}}
    clipped = [v['view'] for v in views if 'clip' in v]
    if clipped:
        item['tags']['clipped_views'] = clipped
    script = Path(scripts) / script_id / 'script.json' if scripts else None
    cfg = (json.loads(script.read_text(encoding='utf-8')).get('generator') or {}).get('config') or {} if script and script.is_file() else {}
    item['tags']['pool'] = cfg.get('pool') or 'unlabeled'
    if 'capabilities' in row:
        item['capabilities'] = row['capabilities']
    if kind == 'sector':
        item['tags']['granularity'] = f"sector{len(spec['options'])}"
    if kind == 'map':
        item['images'] = render_maps(row, spec, scripts, script_id, out)
    elif (row.get('presentation') or {}).get('images'):
        item['images'] = attached_images(row, script_id, out, source_dir)
    truth = {'item_id': item_id, 'truth': np_answers.truth_of(row, spec)}
    return item, truth


def attached_images(row, script_id, out, source_dir):
    """Copy the PNGs the prover attached to this row (presentation.images, paths relative to the question file's
    directory) into out/maps/<script_id>/ and return them as item images. The question text points at the figure
    (floor-plan location with A–D markers, map scaffolds), so a missing file skips the row instead of asking blind."""
    images = []
    for image in row['presentation']['images']:
        src = Path(source_dir) / image['path'] if source_dir else None
        if src is None or not src.is_file():
            raise np_answers.AnswerError('attached image missing')
        dst = out / 'maps' / script_id / image['path']
        dst.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy2(src, dst)
        images.append({'role': image.get('role', 'map'), **({'label': image['label']} if image.get('label') else {}),
                       'path': str(dst.relative_to(out))})
    return images


def sample_rows(question_files, per_version, seed):
    """Seeded sample of at most ``per_version`` PASS rows per version, spread over scripts in turn.

    Returns {(file, line_no)} to keep. Each version's rows are shuffled per script with ``seed``, then
    taken round-robin across scripts so one long script does not fill the version's share.
    """
    pools = collections.defaultdict(lambda: collections.defaultdict(list))
    for qf in question_files:
        with storage.open_read(qf) as fh:
            for n, line in enumerate(fh):
                if line.strip():
                    row = json.loads(line)
                    if row.get('decision', {}).get('result') == 'PASS':
                        pools[row['public']['version_id']][str(qf)].append(n)
    keep = set()
    for vid in sorted(pools):
        lanes = []
        for qf in sorted(pools[vid]):
            lines = pools[vid][qf][:]
            random.Random(f'{seed}|{vid}|{Path(qf).parent.name}').shuffle(lines)
            lanes.append([(qf, n) for n in lines])
        picked = []
        while len(picked) < per_version and any(lanes):
            for lane in lanes:
                if lane and len(picked) < per_version:
                    picked.append(lane.pop(0))
        keep.update(picked)
    return keep


def pass_rows(question_files, keep=None):
    """Denominator D0, counted apart from the export loop: PASS rows (after the sample filter) per version."""
    d0 = collections.Counter()
    for qf in question_files:
        with storage.open_read(qf) as fh:
            for n, line in enumerate(fh):
                if line.strip() and (keep is None or (str(qf), n) in keep):
                    row = json.loads(line)
                    d0[row['public']['version_id']] += row.get('decision', {}).get('result') == 'PASS'
    return +d0


def select_rows(question_files, item_ids):
    """{(file, line_no)} of the PASS rows whose exported item_id is listed; every listed id must be found."""
    want, keep, found = set(item_ids), set(), set()
    for qf in question_files:
        script_id = Path(qf).parent.name
        with storage.open_read(qf) as fh:
            for n, line in enumerate(fh):
                if line.strip():
                    row = json.loads(line)
                    iid = f"{script_id}/{row['candidate_id']}"
                    if iid in want and row.get('decision', {}).get('result') == 'PASS':
                        keep.add((str(qf), n))
                        found.add(iid)
    if want - found:
        lost = sorted(want - found)
        raise SystemExit(f'{len(lost)} listed item ids not found as PASS rows, e.g. {lost[:3]}')
    return keep


def read_item_ids(path):
    """item_id of every row in a jsonl file (e.g. a review set's questions.jsonl)."""
    with open(path, encoding='utf-8') as fh:
        return [json.loads(line)['item_id'] for line in fh if line.strip()]


def export(question_files, out, videos=None, scripts=None, limit_per_version=None, sample=None, seed=0,
           clips=None, item_ids=None):
    out = Path(out)
    if out.exists() and any(out.iterdir()):
        raise SystemExit(f'{out} is not empty; every export goes to a fresh directory')
    out.mkdir(parents=True, exist_ok=True)
    counts = collections.Counter()
    kinds = collections.defaultdict(collections.Counter)
    skipped = collections.defaultdict(collections.Counter)
    no_video = collections.Counter()
    seen = set()
    if sample and item_ids is not None:
        raise SystemExit('--sample-per-version and --items-from are exclusive')
    keep = sample_rows(question_files, sample, seed) if sample else None
    if item_ids is not None:
        keep = select_rows(question_files, item_ids)
    clip_index = load_clips(clips)
    clipped_views = 0
    d0 = pass_rows(question_files, keep)
    with open(out / 'items.jsonl', 'w', encoding='utf-8') as items, \
            open(out / 'truth.jsonl', 'w', encoding='utf-8') as truths:
        for qf in question_files:
            qf = Path(qf)
            script_id = qf.parent.name
            with storage.open_read(qf) as fh:
                for n, line in enumerate(fh):
                    if not line.strip() or (keep is not None and (str(qf), n) not in keep):
                        continue
                    row = json.loads(line)
                    vid = row['public']['version_id']
                    if row.get('decision', {}).get('result') != 'PASS':
                        skipped[vid]['not PASS'] += 1
                        continue
                    if limit_per_version and counts[vid] >= limit_per_version:
                        skipped[vid]['over limit_per_version'] += 1
                        continue
                    try:
                        item, truth = item_of(row, script_id, out, videos, scripts, clips=clip_index, source_dir=qf.parent)
                    except np_answers.AnswerError as exc:
                        skipped[vid][str(exc)] += 1
                        continue
                    if item['item_id'] in seen:
                        skipped[vid]['duplicate item id'] += 1
                        continue
                    seen.add(item['item_id'])
                    # 收据回查用:出处行号;支架种类(空表=不给,旧题没记的记 unrecorded),按组统计用
                    item['src'] = f'{script_id}/{qf.name.removesuffix(".zst")}:{n + 1}'
                    scaffold = row['public'].get('scaffold')
                    item['tags']['scaffold'] = 'unrecorded' if scaffold is None else '+'.join(scaffold) or 'none'
                    counts[vid] += 1
                    clipped_views += len(item['tags'].get('clipped_views', []))
                    kinds[item['tags']['answer_kind']][vid] += 1
                    no_video[vid] += not item['tags']['has_video']
                    items.write(json.dumps(item, ensure_ascii=False) + '\n')
                    truths.write(json.dumps(truth, ensure_ascii=False) + '\n')
    report = {'schema': 'np-evaluation-export/1', 'sources': [str(Path(q).resolve()) for q in question_files],
              'videos': str(videos) if videos else None,
              'clips': {'index': str(clips), 'available': len(clip_index), 'views_sent_as_clips': clipped_views}
              if clips else None,
              'selection': {'item_ids': len(item_ids)} if item_ids is not None else None,
              'items': sum(counts.values()),
              'versions': len(counts), 'per_version': dict(sorted(counts.items())),
              'per_kind': {k: sum(v.values()) for k, v in sorted(kinds.items())},
              'without_video': sum(no_video.values()),
              'sample': {'per_version': sample, 'seed': seed} if sample else None,
              'skipped': {k: dict(v) for k, v in sorted(skipped.items())},
              'denominator': {'pass_rows': sum(d0.values()), 'items': sum(counts.values()),
                              'skipped_pass': sum(c for v in skipped.values() for r, c in v.items() if r != 'not PASS')},
              'scope': 'Public items and private truth exported from prover packages; '
                       'item qualification, sampling to the benchmark quotas and rendering checks are not done here.'}
    (out / 'export.json').write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
    den = report['denominator']
    if den['pass_rows'] != den['items'] + den['skipped_pass']:
        raise SystemExit(f"denominator mismatch: {den['pass_rows']} PASS rows != {den['items']} items + "
                         f"{den['skipped_pass']} skipped (export.json)")
    return report


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])
    ap.add_argument('--questions', nargs='+', required=True, help='questions.jsonl files (parent dir = script id)')
    ap.add_argument('--out', required=True)
    ap.add_argument('--videos', help='batch RUN root, <script_id>/<observer>.mp4 root, or videos directory; '
                    'missing recordings are errors (omit for text-only export)')
    ap.add_argument('--scripts', help='generator root holding <script_id>/script.json (map items)')
    ap.add_argument('--limit-per-version', type=int, help='first N rows per version, in file order')
    ap.add_argument('--sample-per-version', type=int, help='seeded random N rows per version, balanced over scripts')
    ap.add_argument('--seed', type=int, default=0)
    ap.add_argument('--clips', help='clips/index.json (np-review-clips/1) for rows whose recording_views crop a '
                    'recording; a cropped view without a clip is an error')
    ap.add_argument('--items-from', help='jsonl whose item_id rows select the PASS rows to export')
    args = ap.parse_args(argv)
    report = export(args.questions, args.out, args.videos, args.scripts, args.limit_per_version,
                    args.sample_per_version, args.seed, args.clips,
                    read_item_ids(args.items_from) if args.items_from else None)
    print(json.dumps({k: report[k] for k in ('items', 'versions', 'per_kind', 'without_video')}, ensure_ascii=False))
    if report['skipped']:
        print('skipped:', json.dumps(report['skipped'], ensure_ascii=False, indent=1))


if __name__ == '__main__':
    main()