Datasets:
Download code/scripts/manual_dialogue_pilot.py from kuramot6f/classical-ja-pretrain: direct link, hf CLI and curl.
- Browser
- Download file 12.3 kB
-
https://huggingface.co/datasets/kuramot6f/classical-ja-pretrain/resolve/main/code/scripts/manual_dialogue_pilot.py
- Command line
-
hf download hf://datasets/kuramot6f/classical-ja-pretrain/code/scripts/manual_dialogue_pilot.py
-
curl -L -o manual_dialogue_pilot.py https://huggingface.co/datasets/kuramot6f/classical-ja-pretrain/resolve/main/code/scripts/manual_dialogue_pilot.py
12.3 kB
| #!/usr/bin/env python3 | |
| """Offline source dossiers and explicitly reviewed edits. Never calls an API.""" | |
| import argparse | |
| from collections import Counter, defaultdict | |
| import difflib | |
| import json | |
| from pathlib import Path | |
| import re | |
| import sqlite3 | |
| import extract_dialogues as ex | |
| RUN = Path(__file__).resolve().parents[1] / 'unified/sft-dialogue-v1/build-openai-001' | |
| OUT = RUN / 'repair-manual-100-001' | |
| MARKER = re.compile(r'【\s*NDLJP:[^】]*】') | |
| def compact(text): | |
| ignored = set() | |
| for m in MARKER.finditer(text): | |
| ignored.update(range(m.start(), m.end())) | |
| mapping = [i for i, c in enumerate(text) if not c.isspace() and i not in ignored] | |
| return ''.join(text[i] for i in mapping), mapping | |
| def locate(text, quote): | |
| needle, _ = compact(quote) | |
| source, mapping = compact(text) | |
| positions, at = [], 0 | |
| while needle: | |
| pos = source.find(needle, at) | |
| if pos < 0: | |
| break | |
| positions.append([mapping[pos], mapping[pos + len(needle) - 1] + 1]) | |
| at = pos + 1 | |
| return positions | |
| def dossier(sample, db): | |
| old = sample['candidate'] | |
| seg = db.execute('SELECT * FROM segments WHERE id=?', (old['segment_id'],)).fetchone() | |
| chunk = db.execute('SELECT * FROM chunks WHERE id=?', (old['chunk_id'],)).fetchone() | |
| start, end = max(0, chunk['start'] - 2000), min(len(seg['text']), chunk['end'] + 2000) | |
| source = seg['text'][start:end] | |
| draft, anchors = [], [] | |
| for turn in old['turns']: | |
| matches = locate(source, turn['text']) | |
| if len(matches) == 1: | |
| s, e = matches[0] | |
| draft.append(dict(speaker=turn['speaker'], start=s + start, end=e + start)) | |
| anchors.append((s, e)) | |
| else: | |
| draft.append(None) | |
| needle, _ = compact(turn['text']) | |
| src, mapping = compact(source) | |
| block = difflib.SequenceMatcher(None, needle, src, autojunk=False).find_longest_match() | |
| if block.size: | |
| s = mapping[max(0, block.b - block.a)] | |
| e = mapping[min(len(mapping) - 1, block.b + len(needle) - block.a - 1)] + 1 | |
| anchors.append((s, e)) | |
| return dict(**sample, context_start=start, context_end=end, text=source, | |
| source_sha256=ex.digest(source), draft=draft, | |
| anchors=[[s + start, e + start] for s, e in anchors]) | |
| def prepare(): | |
| OUT.mkdir(exist_ok=False) | |
| (OUT / 'dossiers').mkdir() | |
| samples = list(ex.iter_jsonl(RUN / 'repair-pilot-100-001/sample.jsonl')) | |
| with sqlite3.connect(f'file:{RUN}/state.sqlite3?mode=ro', uri=True) as db: | |
| db.row_factory = sqlite3.Row | |
| for sample in samples: | |
| ex.write_json(OUT / 'dossiers' / (sample['sample_id'] + '.json'), dossier(sample, db)) | |
| ex.write_json(OUT / 'manifest.json', dict( | |
| created=ex.now(), reviewer='Codex, direct source review', model_api_calls=0, | |
| sample_origin='Same original 100-scene sample as preceding pilot; API repair outputs are not inputs.', | |
| original_sha256={name: ex.file_hash(RUN / name) for name in ( | |
| 'exports/001/review.jsonl', 'exports/001/dialogues.jsonl', | |
| 'exports/001/provenance.jsonl', 'state.sqlite3')}, | |
| sample_sha256=ex.file_hash(RUN / 'repair-pilot-100-001/sample.jsonl'), | |
| script_sha256=ex.file_hash(__file__))) | |
| ex.write_json(OUT / 'edits.json', {}) | |
| def show(ids): | |
| for sid in ids: | |
| d = ex.read_json(OUT / 'dossiers' / (sid.zfill(3) + '.json')) | |
| c = d['candidate'] | |
| print('\n###', d['sample_id'], c['title'], c['review_reason']) | |
| for i, (turn, draft) in enumerate(zip(c['turns'], d['draft'])): | |
| print('OLD', i, turn['speaker'], repr(turn['text']), 'DRAFT', draft) | |
| # Merge nearby anchor excerpts; offsets refer to the complete segment. | |
| intervals = [] | |
| for s, e in sorted(d['anchors']): | |
| s, e = max(d['context_start'], s - 180), min(d['context_end'], e + 180) | |
| if intervals and s <= intervals[-1][1] + 200: | |
| intervals[-1][1] = max(intervals[-1][1], e) | |
| else: | |
| intervals.append([s, e]) | |
| for s, e in intervals: | |
| print('SOURCE', s, e) | |
| print(d['text'][s - d['context_start']:e - d['context_start']]) | |
| def resolve_selection(d, turn): | |
| text = d['text'] | |
| if 'old' in turn: | |
| span = d['draft'][turn['old']] | |
| if span is None: | |
| raise ValueError('Old turn has no unique exact alignment') | |
| s, e = span['start'], span['end'] | |
| speaker = turn.get('speaker', span['speaker']) | |
| elif 'start' in turn: | |
| s, e, speaker = turn['start'], turn['end'], turn['speaker'] | |
| else: | |
| # Explicit reviewer-specified verbatim boundary strings; no fuzzy edits. | |
| begins, ends = turn['begin'], turn['end_quote'] | |
| low = turn.get('after', d['context_start']) - d['context_start'] | |
| hits = [m.start() for m in re.finditer(re.escape(begins), text) if m.start() >= low] | |
| if len(hits) != 1 and 'occurrence' not in turn: | |
| raise ValueError(f'Ambiguous begin {begins!r}: {hits}') | |
| s = hits[turn.get('occurrence', 0)] | |
| e0 = text.find(ends, s) | |
| if e0 < 0: | |
| raise ValueError(f'End not found {ends!r}') | |
| e = e0 + len(ends) | |
| s += d['context_start']; e += d['context_start'] | |
| speaker = turn['speaker'] | |
| assert d['context_start'] <= s < e <= d['context_end'] | |
| # Page-location tags are editorial metadata, not spoken text. Represent | |
| # interrupted quotation as consecutive turns by the same speaker. | |
| quote = text[s - d['context_start']:e - d['context_start']] | |
| pieces, at = [], 0 | |
| for marker in list(MARKER.finditer(quote)) + [None]: | |
| stop = marker.start() if marker else len(quote) | |
| a, b = at, stop | |
| while a < b and quote[a].isspace(): | |
| a += 1 | |
| while b > a and quote[b - 1].isspace(): | |
| b -= 1 | |
| if a < b: | |
| pieces.append((speaker, s + a, s + b)) | |
| if marker: | |
| at = marker.end() | |
| return pieces | |
| def export(): | |
| manifest = ex.read_json(OUT / 'manifest.json') | |
| for name, sha in manifest['original_sha256'].items(): | |
| assert ex.file_hash(RUN / name) == sha, name | |
| edits = ex.read_json(OUT / 'edits.json') | |
| assert set(edits) == {f'{i:03d}' for i in range(1, 101)}, 'All 100 need an explicit decision' | |
| accepted = list(ex.iter_jsonl(RUN / 'exports/001/dialogues.jsonl')) | |
| decisions, candidates = [], [] | |
| with sqlite3.connect(f'file:{RUN}/state.sqlite3?mode=ro', uri=True) as db: | |
| db.row_factory = sqlite3.Row | |
| for sid, edit in sorted(edits.items()): | |
| d = ex.read_json(OUT / 'dossiers' / (sid + '.json')) | |
| assert ex.digest(d['text']) == d['source_sha256'] | |
| row = {k: d[k] for k in ('sample_id', 'original_line', 'candidate')} | |
| row.update(status=edit['status'], reason=edit['reason'], reviewer='Codex direct review') | |
| assert row['status'] in ('repaired', 'rejected', 'unresolved', 'duplicate_sample') | |
| if row['status'] == 'duplicate_sample': | |
| row['duplicate_of_sample_id'] = edit['duplicate_of_sample_id'] | |
| if row['status'] == 'repaired': | |
| spans = [span for turn in edit['turns'] for span in resolve_selection(d, turn)] | |
| assert all(a[2] <= b[1] for a, b in zip(spans, spans[1:])), sid | |
| names, turns = {}, [] | |
| for speaker, s, e in spans: | |
| names.setdefault(speaker, chr(65 + len(names))) | |
| turns.append(dict(speaker=names[speaker], text=d['text'][s-d['context_start']:e-d['context_start']])) | |
| assert len(names) >= 2, sid | |
| old = d['candidate'] | |
| item = {k: v for k, v in old.items() if k not in ('review_reason', 'segment_spans', 'turn_source_spans')} | |
| item.update(turns=turns, segment_spans=[[s, e] for _, s, e in spans], repair_sample_id=sid) | |
| seg = db.execute('SELECT * FROM segments WHERE id=?', (old['segment_id'],)).fetchone() | |
| records = json.loads(seg['records']) | |
| item['turn_source_spans'] = [ex.source_spans(records, s, e) for _, s, e in spans] | |
| for turn, (_, s, e) in zip(turns, spans): | |
| assert seg['text'][s:e] == turn['text'], sid | |
| item['record_ids'] = list(dict.fromkeys(s['record_id'] for ss in item['turn_source_spans'] for s in ss)) | |
| item['scene_id'] = ex.digest(ex.encode([item['segment_id'], item['segment_spans'], turns])) | |
| item['context_dependence'] = edit.get('context_dependence', old['context_dependence']) | |
| item['extraction_confidence'] = edit.get('extraction_confidence', old['extraction_confidence']) | |
| item['score_origin'] = 'original extraction; inherited unless explicitly reviewed' | |
| row['repaired'] = item | |
| candidates.append(row) | |
| decisions.append(row) | |
| def overlap(a, b): | |
| return (a['segment_id'] == b['segment_id'] and a['segment_spans'][0][0] < b['segment_spans'][-1][1] | |
| and b['segment_spans'][0][0] < a['segment_spans'][-1][1]) | |
| def sig(a): | |
| return ex.encode([a['segment_spans'], a['turns']]) | |
| for row in candidates: | |
| item = row['repaired'] | |
| collisions = [a for a in accepted if overlap(item, a)] | |
| if any(sig(a) == sig(item) for a in collisions): | |
| row.update(status='duplicate_existing', duplicate_of=[a['scene_id'] for a in collisions if sig(a) == sig(item)]) | |
| elif collisions: | |
| row.update(status='unresolved', original_review_decision='repaired', | |
| reason=row['reason'] + '/既存候補との範囲競合が残るため保留。', | |
| conflicts=[a['scene_id'] for a in collisions]) | |
| for i, row in enumerate(candidates): | |
| if row['status'] != 'repaired': | |
| continue | |
| for other in candidates[i+1:]: | |
| if other['status'] == 'repaired' and overlap(row['repaired'], other['repaired']): | |
| row.update(status='unresolved', reason=row['reason'] + '/試行内の別修正と範囲が競合。') | |
| other.update(status='unresolved', reason=other['reason'] + '/試行内の別修正と範囲が競合。') | |
| def jsonl(name, rows): | |
| (OUT / name).write_text(''.join(ex.encode(r)+'\n' for r in rows), encoding='utf-8') | |
| jsonl('decisions.jsonl', decisions) | |
| repaired = [r['repaired'] for r in decisions if r['status'] == 'repaired'] | |
| jsonl('dialogues.jsonl', repaired) | |
| for name, statuses in [('review', {'unresolved'}), ('rejected', {'rejected'}), ('duplicates', {'duplicate_existing', 'duplicate_sample'})]: | |
| jsonl(name+'.jsonl', [r for r in decisions if r['status'] in statuses]) | |
| segment_ids = {i['segment_id'] for i in repaired} | |
| jsonl('provenance.jsonl', [r for r in ex.iter_jsonl(RUN / 'exports/001/provenance.jsonl') if r['segment_id'] in segment_ids]) | |
| by_reason = defaultdict(Counter) | |
| for r in decisions: | |
| by_reason[r['candidate']['review_reason']][r['status']] += 1 | |
| report = dict(sample_size=100, model_api_calls=0, reviewer='Codex direct source review', | |
| statuses=dict(Counter(r['status'] for r in decisions)), | |
| by_original_reason={k:dict(v) for k,v in by_reason.items()}, | |
| repaired_scenes=len(repaired), repaired_turns=sum(len(i['turns']) for i in repaired), | |
| all_turns_verbatim=True, original_inputs_unchanged=True, | |
| remaining_unsampled_review_scenes=1677, | |
| original_export_not_merged=True, edits_sha256=ex.file_hash(OUT/'edits.json'), | |
| file_sha256={p.name:ex.file_hash(p) for p in OUT.glob('*.jsonl')}) | |
| ex.write_json(OUT/'report.json', report) | |
| print(json.dumps(report, ensure_ascii=False, indent=2)) | |
| if __name__ == '__main__': | |
| p = argparse.ArgumentParser(description=__doc__) | |
| p.add_argument('command', choices=['prepare', 'show', 'export']) | |
| p.add_argument('ids', nargs='*') | |
| a = p.parse_args() | |
| if a.command == 'prepare': prepare() | |
| elif a.command == 'show': show(a.ids) | |
| else: export() | |