File size: 2,932 Bytes
7ff74f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Add angle responses to frozen proved direction questions, preserving all input rows.

python3 -B -m np.direction_angles --questions VOUT/SEG/groups.jsonl \
    --segment SEGS/SEG --out NEW/SEG/groups.jsonl

Use the new file with the ordinary evaluation exporter. Each angle question has
its own candidate identity and proof; the frozen sector row is copied unchanged.
"""
import argparse
import collections
import json
import shutil
from pathlib import Path

import numpy as np

from embodied_pipeline.prover.direction_angles import angle_question
from np.proof_storage import compact, expand


def augment(source, segment, out):
    """Write originals and their angle variants; report every failed candidate."""
    script = json.loads((segment/'script.json').read_text())
    counts, failures = collections.Counter(), []
    out.parent.mkdir(parents=True, exist_ok=True)
    with np.load(segment/'curves.npz', allow_pickle=False) as curves, source.open() as src, out.open('x') as dst:
        for line in src:
            stored = json.loads(line)
            dst.write(line if line.endswith('\n') else line+'\n')
            counts['original'] += 1
            row = expand(stored)
            # Exporters resolve attached figures beside their question file.
            # Keep available original figures when writing a new directory.
            for image in row.get('presentation', {}).get('images', []):
                original, target = source.parent/image['path'], out.parent/image['path']
                if original.is_file() and original.resolve() != target.resolve():
                    target.parent.mkdir(parents=True, exist_ok=True)
                    shutil.copy2(original, target)
            try:
                angle = angle_question(row, script, curves)
                if angle is None:
                    continue
                if angle['decision']['result'] != 'PASS':
                    raise ValueError('angle decision: '+json.dumps(angle['decision'], ensure_ascii=False))
                dst.write(json.dumps(compact(angle), ensure_ascii=False)+'\n')
                counts[angle['public']['version_id']] += 1
            except (KeyError, ValueError, StopIteration) as exc:
                failures.append(dict(candidate_id=row['candidate_id'], error=str(exc)))
    return dict(counts=dict(counts), failed=failures)


def main(argv=None):
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('--questions', type=Path, required=True)
    p.add_argument('--segment', type=Path, required=True)
    p.add_argument('--out', type=Path, required=True)
    a = p.parse_args(argv)
    result = augment(a.questions, a.segment, a.out)
    a.out.with_suffix('.angles.json').write_text(json.dumps(result, ensure_ascii=False, indent=2)+'\n')
    print(json.dumps(result, ensure_ascii=False))
    return int(bool(result['failed']))


if __name__ == '__main__':
    raise SystemExit(main())