File size: 37,074 Bytes
7a088d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
#!/usr/bin/env python3
"""Resumable DeepSeek/OpenAI dialogue extraction. Python 3.10+, standard library only."""
from __future__ import annotations

import argparse
import bisect
from collections import Counter, defaultdict
from concurrent.futures import ThreadPoolExecutor, wait, FIRST_COMPLETED
from contextlib import contextmanager
from datetime import datetime, timezone
import fcntl
import hashlib
import json
from pathlib import Path
import re
import sqlite3
import sys
import time
import urllib.error
import urllib.request

ROOT = Path(__file__).resolve().parents[1]
DEFAULT_CONFIG = Path(__file__).with_name('dialogue_extraction_config.json')
DEEPSEEK_API_KEY = "<REDACTED>"  # Set your DeepSeek API key here.
VERSION = 1
OPENAI_API_KEY = '<REDACTED>'  # OpenAI API key.


def encode(value):
    return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':'))


def digest(value):
    return hashlib.sha256(value.encode('utf-8')).hexdigest()


def file_hash(path):
    h = hashlib.sha256()
    with open(path, 'rb') as f:
        for block in iter(lambda: f.read(1024 * 1024), b''):
            h.update(block)
    return h.hexdigest()


def now():
    return datetime.now(timezone.utc).isoformat()


def read_json(path):
    return json.loads(Path(path).read_text(encoding='utf-8'))


def write_json(path, value):
    path = Path(path)
    tmp = path.with_suffix(path.suffix + '.tmp')
    tmp.write_text(json.dumps(value, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
    tmp.replace(path)


def iter_jsonl(path):
    with open(path, encoding='utf-8') as f:
        for number, line in enumerate(f, 1):
            try:
                yield json.loads(line)
            except ValueError as exc:
                raise ValueError(f'{path}:{number}: invalid JSON') from exc


def resolve(path):
    path = Path(path)
    return path.resolve() if path.is_absolute() else (ROOT / path).resolve()


@contextmanager
def locked(run):
    with open(run / '.lock', 'a') as lock:
        try:
            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError as exc:
            raise ValueError('Another process is using this run') from exc
        yield


def connect(run):
    db = sqlite3.connect(run / 'state.sqlite3')
    db.row_factory = sqlite3.Row
    return db


def load_config(path):
    cfg = read_json(path)
    expected = {'input', 'splits', 'prompt', 'sources', 'splits_include', 'seed',
                'chunk_chars', 'overlap_chars', 'boundary_margin_chars',
                'min_split_chars', 'max_split_depth', 'api'}
    if set(cfg) != expected:
        raise ValueError(f'Config keys must be {sorted(expected)}')
    if not 0 <= cfg['overlap_chars'] < cfg['chunk_chars'] // 2:
        raise ValueError('Require 0 <= overlap_chars < chunk_chars / 2')
    if cfg['chunk_chars'] < 100 or cfg['min_split_chars'] < 100:
        raise ValueError('Chunk sizes must be at least 100 characters')
    if cfg['boundary_margin_chars'] < 0 or cfg['max_split_depth'] < 0:
        raise ValueError('Boundary margin and max split depth must be nonnegative')
    if not cfg['sources'] or not set(cfg['sources']) <= {'minhon', 'wikisource'}:
        raise ValueError('Unsupported or empty sources')
    if not cfg['splits_include'] or not set(cfg['splits_include']) <= {'train', 'validation', 'test'}:
        raise ValueError('Invalid splits_include')
    api = cfg['api']
    api_keys = {'base_url', 'model', 'thinking', 'temperature', 'max_tokens',
                'timeout_seconds', 'workers', 'attempts_per_invocation', 'retry_base_seconds'}
    if set(api) - {'reasoning_effort', 'provider', 'response_format'} != api_keys:
        raise ValueError(f'API config keys must be {sorted(api_keys)}; reasoning_effort, provider and response_format are optional')
    if api.get('provider', 'deepseek') not in ('deepseek', 'openai'):
        raise ValueError('api.provider must be deepseek or openai')
    response_format = api.get('response_format', {'type': 'json_object'})
    if not isinstance(response_format, dict) or response_format.get('type') not in ('json_object', 'json_schema'):
        raise ValueError('api.response_format must specify json_object or json_schema')
    if response_format['type'] == 'json_schema':
        schema = response_format.get('json_schema')
        if api.get('provider', 'deepseek') != 'openai':
            raise ValueError('json_schema output is currently supported only for provider=openai')
        if not isinstance(schema, dict) or schema.get('strict') is not True or not isinstance(schema.get('schema'), dict):
            raise ValueError('json_schema output requires strict=true and a schema object')
    if 'reasoning_effort' in api and api['reasoning_effort'] not in ('low', 'high', 'max'):
        raise ValueError('api.reasoning_effort must be low, high, or max')
    for key in ('max_tokens', 'timeout_seconds', 'workers', 'attempts_per_invocation'):
        if api[key] <= 0:
            raise ValueError(f'api.{key} must be positive')
    if api['retry_base_seconds'] < 0 or api['thinking'] not in ('enabled', 'disabled'):
        raise ValueError('Invalid API retry/thinking configuration')
    for key in ('input', 'splits', 'prompt'):
        cfg[key] = str(resolve(cfg[key]))
    return cfg


def chunk_ranges(text, size, overlap):
    start = 0
    while start < len(text):
        end = min(start + size, len(text))
        if end < len(text):
            cut = text.rfind('\n', start + size // 2, end)
            if cut >= 0:
                end = cut + 1
        yield start, end
        if end == len(text):
            break
        start = end - overlap


def page_number(doc):
    """Only explicit numeric page filenames establish adjacency; unknowns stay separate."""
    label = doc.get('unit_label') or ''
    match = re.fullmatch(r'(\d+)\.txt', label)
    return int(match[1]) if match else None


def ordered_segments(docs):
    if docs[0]['source'] != 'minhon':
        return [[doc] for doc in sorted(docs, key=lambda d: d['id'])]
    numbers = [page_number(doc) for doc in docs]
    if None in numbers or len(numbers) != len(set(numbers)):
        return [[doc] for doc in sorted(docs, key=lambda d: d['id'])]
    segments = []
    previous = None
    for doc in sorted(docs, key=page_number):
        number = page_number(doc)
        if previous is None or number != previous + 1:
            segments.append([])
        segments[-1].append(doc)
        previous = number
    return segments


def join_segment(docs):
    parts, records, offset = [], [], 0
    for doc in docs:
        if parts:
            parts.append('\n')
            offset += 1
        text = doc['text']
        records.append({'id': doc['id'], 'start': offset, 'end': offset + len(text),
                        'text_sha256': digest(text),
                        'metadata': {k: v for k, v in doc.items() if k != 'text'}})
        parts.append(text)
        offset += len(text)
    return ''.join(parts), records


def insert_chunk(db, segment_id, text, start, end, parent=None, depth=0):
    identity = {'segment_id': segment_id, 'start': start, 'end': end,
                'text_sha256': digest(text[start:end])}
    chunk_id = digest(encode(identity))
    db.execute('INSERT OR IGNORE INTO chunks VALUES (?,?,?,?,?,?,?,?,?,?)',
               (chunk_id, segment_id, start, end, identity['text_sha256'], parent,
                depth, 'pending', 0, None))
    return chunk_id


def prepare(args):
    cfg = load_config(args.config)
    if args.limit_works_per_source is not None and args.limit_works_per_source < 1:
        raise ValueError('--limit-works-per-source must be positive')
    run = args.run.resolve()
    run.mkdir(parents=True, exist_ok=False)
    manifest = {'version': VERSION, 'complete': False, 'started': now(), 'config': cfg,
                'limit_works_per_source': args.limit_works_per_source}
    write_json(run / 'manifest.json', manifest)
    with locked(run), connect(run) as db:
        db.executescript('''
        CREATE TABLE docs (id TEXT PRIMARY KEY, source TEXT, work_id TEXT, data TEXT);
        CREATE INDEX docs_work ON docs(source,work_id);
        CREATE TABLE splits (id TEXT PRIMARY KEY, data TEXT);
        CREATE TABLE segments (id TEXT PRIMARY KEY, source TEXT, work_id TEXT,
          split TEXT, work_group TEXT, title TEXT, text TEXT, records TEXT);
        CREATE TABLE chunks (id TEXT PRIMARY KEY, segment_id TEXT, start INTEGER,
          end INTEGER, text_sha256 TEXT, parent TEXT, depth INTEGER,
          status TEXT, attempts INTEGER, error TEXT);
        CREATE INDEX chunk_status ON chunks(status);
        CREATE TABLE attempts (id INTEGER PRIMARY KEY, chunk_id TEXT,
          started TEXT, finished TEXT, status TEXT, raw_path TEXT, error TEXT, usage TEXT);
        ''')
        print('Reading source records...', flush=True)
        for doc in iter_jsonl(cfg['input']):
            if doc.get('source') not in cfg['sources']:
                continue
            if not isinstance(doc.get('text'), str) or not doc['text']:
                raise ValueError(f'Empty/invalid text: {doc.get("id")}')
            if doc.get('text_sha256') and digest(doc['text']) != doc['text_sha256']:
                raise ValueError(f'Text hash mismatch: {doc["id"]}')
            work_id = doc.get('source_document_id') or doc['id']
            db.execute('INSERT INTO docs VALUES (?,?,?,?)',
                       (doc['id'], doc['source'], work_id, encode(doc)))
        for split in iter_jsonl(cfg['splits']):
            if split.get('source') in cfg['sources']:
                db.execute('INSERT INTO splits VALUES (?,?)', (split['id'], encode(split)))
        candidates = defaultdict(list)
        for row in db.execute('SELECT DISTINCT source,work_id FROM docs'):
            candidates[row['source']].append(row['work_id'])
        counts = Counter()
        for source in sorted(candidates):
            works = sorted(candidates[source], key=lambda w: (digest(f'{cfg["seed"]}:{source}:{w}'), w))
            selected = 0
            for work_id in works:
                rows = db.execute('SELECT d.data,s.data AS split_data FROM docs d '
                                  'LEFT JOIN splits s ON d.id=s.id WHERE d.source=? AND d.work_id=?',
                                  (source, work_id)).fetchall()
                docs, assignments = [], set()
                for row in rows:
                    doc = json.loads(row['data'])
                    if row['split_data'] is None:
                        raise ValueError(f'Missing split: {doc["id"]}')
                    split = json.loads(row['split_data'])
                    if split.get('text_sha256') != digest(doc['text']):
                        raise ValueError(f'Split/input text mismatch: {doc["id"]}')
                    assignments.add((split['split'], split['group']))
                    docs.append(doc)
                if len(assignments) != 1:
                    raise ValueError(f'Inconsistent group/split inside work: {work_id}')
                split_name, group = next(iter(assignments))
                if split_name not in cfg['splits_include']:
                    continue
                if args.limit_works_per_source is not None and selected >= args.limit_works_per_source:
                    break
                selected += 1
                counts[f'{source}.works'] += 1
                for part in ordered_segments(docs):
                    text, records = join_segment(part)
                    segment_id = digest(encode([source, work_id, [d['id'] for d in part]]))
                    db.execute('INSERT INTO segments VALUES (?,?,?,?,?,?,?,?)',
                               (segment_id, source, work_id, split_name, group,
                                part[0].get('title'), text, encode(records)))
                    for start, end in chunk_ranges(text, cfg['chunk_chars'], cfg['overlap_chars']):
                        insert_chunk(db, segment_id, text, start, end)
                        counts[f'{source}.chunks'] += 1
                    counts[f'{source}.segments'] += 1
        # Keep only records that are actually part of this frozen extraction run.
        db.execute('DROP TABLE docs')
        db.execute('DROP TABLE splits')
        db.commit()
        prompt = Path(cfg['prompt']).read_text(encoding='utf-8')
        (run / 'prompt.txt').write_text(prompt, encoding='utf-8')
        manifest.update({'complete': True, 'prepared': now(), 'counts': dict(counts),
                         'input_sha256': file_hash(cfg['input']),
                         'splits_sha256': file_hash(cfg['splits']),
                         'prompt_sha256': digest(prompt),
                         'script_sha256': file_hash(__file__)})
        manifest['settings_sha256'] = digest(encode(cfg))
        write_json(run / 'manifest.json', manifest)
    print(json.dumps({'run': str(run), 'counts': counts}, ensure_ascii=False, indent=2))


def load_run(run):
    manifest = read_json(run / 'manifest.json')
    if not manifest.get('complete') or manifest.get('version') != VERSION:
        raise ValueError('Run preparation is incomplete or version is unsupported')
    if digest(encode(manifest['config'])) != manifest['settings_sha256']:
        raise ValueError('Frozen run settings were modified; prepare a new run')
    prompt = (run / 'prompt.txt').read_text(encoding='utf-8')
    if digest(prompt) != manifest['prompt_sha256']:
        raise ValueError('Frozen prompt was modified; prepare a new run')
    return manifest, prompt


def strict_json(text):
    def pairs(items):
        result = {}
        for k, v in items:
            if k in result:
                raise ValueError(f'Duplicate JSON key: {k}')
            result[k] = v
        return result
    return json.loads(text, object_pairs_hook=pairs)


def parse_scenes(content):
    value = strict_json(content)
    if not isinstance(value, dict) or set(value) != {'scenes'} or not isinstance(value['scenes'], list):
        raise ValueError('Expected JSON object with scenes array')
    for scene in value['scenes']:
        if not isinstance(scene, dict) or set(scene) != {'context_dependence', 'extraction_confidence', 'turns'}:
            raise ValueError('Invalid scene keys')
        for key in ('context_dependence', 'extraction_confidence'):
            if type(scene[key]) is not int or not 0 <= scene[key] <= 3:
                raise ValueError(f'Invalid {key}')
        turns = scene['turns']
        if not isinstance(turns, list) or len(turns) < 2:
            raise ValueError('A scene requires at least two turns')
        speakers = []
        for turn in turns:
            if not isinstance(turn, dict) or set(turn) != {'speaker', 'text'}:
                raise ValueError('Invalid turn keys')
            speaker = turn['speaker']
            if not isinstance(speaker, str) or not re.fullmatch('[A-Z]', speaker):
                raise ValueError('Invalid speaker')
            if speaker not in speakers:
                if speaker != chr(65 + len(speakers)):
                    raise ValueError('Speakers must start at A in order of first appearance')
                speakers.append(speaker)
            if not isinstance(turn['text'], str) or not turn['text'].strip():
                raise ValueError('Empty/invalid turn text')
        if len(speakers) < 2:
            raise ValueError('A scene requires at least two distinct speakers')
    return value['scenes']


def locate_turns(text, turns):
    """Resolve the *entire* ordered sequence uniquely, never just first substring matches."""
    states = [(0, 1, [])]  # previous end, path count (capped at 2), unique path
    for turn in turns:
        needle = turn['text']
        positions, at = [], 0
        while True:
            pos = text.find(needle, at)
            if pos < 0:
                break
            positions.append(pos)
            at = pos + 1
            if len(positions) > 2000:
                raise ValueError('Too many matching positions')
        if not positions:
            raise ValueError('Turn text not found verbatim')
        ends = [s[0] for s in states]
        cumulative, total = [], 0
        for _, count, _ in states:
            total += count
            cumulative.append(total)
        next_states = []
        for pos in positions:
            index = bisect.bisect_right(ends, pos) - 1
            if index >= 0:
                count = min(2, cumulative[index])
                path = states[0][2] + [(pos, pos + len(needle))] if count == 1 else None
                next_states.append((pos + len(needle), count, path))
        states = next_states
        if not states:
            raise ValueError('Turn order does not match source')
    if sum(s[1] for s in states) != 1:
        raise ValueError('Ambiguous source positions')
    return states[0][2]


class APIError(Exception):
    def __init__(self, message, retryable=True, retry_after=0):
        super().__init__(message)
        self.retryable = retryable
        self.retry_after = retry_after


def call_deepseek(api, prompt, text, key):
    payload = {'model': api['model'], 'messages': [
        {'role': 'system', 'content': prompt},
        {'role': 'user', 'content': '【本文開始】\n' + text + '\n【本文終了】'}],
        'response_format': {'type': 'json_object'}, 'max_tokens': api['max_tokens'],
        'thinking': {'type': api['thinking']}, 'stream': False}
    if api['thinking'] == 'disabled':
        payload['temperature'] = api['temperature']
    elif 'reasoning_effort' in api:
        payload['reasoning_effort'] = api['reasoning_effort']
    return post_chat_completion(api, payload, key)


def call_openai(api, prompt, text, key):
    payload = {'model': api['model'], 'messages': [
        {'role': 'system', 'content': prompt},
        {'role': 'user', 'content': '【本文開始】\n' + text + '\n【本文終了】'}],
        'response_format': api.get('response_format', {'type': 'json_object'}),
        'max_completion_tokens': api['max_tokens'],
        'reasoning_effort': api.get('reasoning_effort', 'low'),
        'store': False, 'stream': False}
    return post_chat_completion(api, payload, key)


def post_chat_completion(api, payload, key):
    url = api['base_url'].rstrip('/') + '/chat/completions'
    req = urllib.request.Request(url, encode(payload).encode('utf-8'), headers={
        'Authorization': 'Bearer ' + key, 'Content-Type': 'application/json'})
    try:
        with urllib.request.urlopen(req, timeout=api['timeout_seconds']) as response:
            raw = response.read().decode('utf-8')
    except urllib.error.HTTPError as exc:
        # Do not echo response bodies or headers: providers may include request details.
        retry_after = exc.headers.get('Retry-After', '0')
        try:
            delay = float(retry_after)
        except ValueError:
            delay = 0
        raise APIError(f'HTTP {exc.code}', exc.code in (408, 409, 429) or exc.code >= 500, delay) from exc
    except (urllib.error.URLError, TimeoutError, OSError) as exc:
        raise APIError(f'Network error: {type(exc).__name__}') from exc
    return raw


def split_truncated(db, chunk, cfg):
    length = chunk['end'] - chunk['start']
    if length <= cfg['min_split_chars'] or chunk['depth'] >= cfg['max_split_depth']:
        return False
    midpoint = (chunk['start'] + chunk['end']) // 2
    overlap = min(cfg['overlap_chars'], length // 4)
    for start, end in ((chunk['start'], midpoint + overlap // 2),
                       (midpoint - overlap // 2, chunk['end'])):
        insert_chunk(db, chunk['segment_id'], chunk['segment_text'], start, end,
                     chunk['id'], chunk['depth'] + 1)
    return True


def chunk_row(db, chunk_id):
    row = db.execute('SELECT c.*,s.text AS segment_text FROM chunks c '
                     'JOIN segments s ON s.id=c.segment_id WHERE c.id=?', (chunk_id,)).fetchone()
    result = dict(row)
    text = result['segment_text'][result['start']:result['end']]
    if digest(text) != result['text_sha256']:
        raise ValueError('Stored chunk text hash mismatch')
    return result


def extract(args, caller=None):
    run = args.run.resolve()
    with locked(run), connect(run) as db:
        manifest, prompt = load_run(run)
        cfg, api = manifest['config'], manifest['config']['api']
        provider = api.get('provider', 'deepseek')
        key = (OPENAI_API_KEY if provider == 'openai' else DEEPSEEK_API_KEY).strip()
        if not key:
            name = 'OPENAI_API_KEY' if provider == 'openai' else 'DEEPSEEK_API_KEY'
            raise ValueError(f'Set the {name} constant in scripts/extract_dialogues.py before extract')
        if caller is None:
            caller = call_openai if provider == 'openai' else call_deepseek
        if args.max_chunks is not None and args.max_chunks < 1:
            raise ValueError('--max-chunks must be positive')
        workers = getattr(args, 'workers', None)
        workers = api['workers'] if workers is None else workers
        if type(workers) is not int or workers < 1:
            raise ValueError('--workers must be a positive integer')
        execution = {'started': now(), 'workers': workers, 'max_chunks': args.max_chunks,
                     'retry_failed': args.retry_failed, 'status': 'running',
                     'script_sha256': file_hash(__file__)}
        (run / 'executions').mkdir(exist_ok=True)
        execution_path = run / 'executions' / (execution['started'].replace(':', '-') + '.json')
        write_json(execution_path, execution)
        # An interrupted request has unknown provider-side completion/billing status.
        db.execute("UPDATE attempts SET status='interrupted',finished=? WHERE status='running'", (now(),))
        db.execute("UPDATE chunks SET status='pending',error='interrupted; previous request may have been billed' WHERE status='running'")
        if args.retry_failed:
            db.execute("UPDATE chunks SET status='pending' WHERE status='failed'")
        db.commit()
        (run / 'responses').mkdir(exist_ok=True)
        scheduled, in_flight, due, tries = set(), {}, {}, Counter()
        stop = False
        print('Extracting (API requests enabled)...', flush=True)
        with ThreadPoolExecutor(max_workers=workers) as pool:
            while True:
                candidates = db.execute("SELECT id FROM chunks WHERE status='pending' ORDER BY rowid").fetchall()
                for row in candidates:
                    cid = row['id']
                    if stop or len(in_flight) >= workers:
                        break
                    if due.get(cid, 0) > time.monotonic():
                        continue
                    if cid not in scheduled and args.max_chunks is not None and len(scheduled) >= args.max_chunks:
                        continue
                    scheduled.add(cid)
                    chunk = chunk_row(db, cid)
                    tries[cid] += 1
                    cursor = db.execute('INSERT INTO attempts(chunk_id,started,status) VALUES (?,?,?)', (cid, now(), 'running'))
                    aid = cursor.lastrowid
                    db.execute("UPDATE chunks SET status='running',attempts=attempts+1 WHERE id=?", (cid,))
                    db.commit()
                    future = pool.submit(caller, api, prompt,
                                         chunk['segment_text'][chunk['start']:chunk['end']], key)
                    in_flight[future] = (chunk, aid)
                if not in_flight:
                    remaining = [r['id'] for r in candidates if r['id'] in scheduled or
                                 args.max_chunks is None or len(scheduled) < args.max_chunks]
                    if stop or not remaining:
                        break
                    time.sleep(min(1, max(0.05, min(due.get(c, 0) for c in remaining) - time.monotonic())))
                    continue
                done, _ = wait(in_flight, timeout=1, return_when=FIRST_COMPLETED)
                for future in done:
                    chunk, aid = in_flight.pop(future)
                    cid, status, error, usage, raw_path = chunk['id'], 'failed', None, {}, None
                    retryable, retry_after = True, 0
                    try:
                        raw = future.result()
                        raw_path = f'responses/{aid:08d}.json'
                        raw_file = run / raw_path
                        raw_file.write_text(raw, encoding='utf-8')
                        envelope = strict_json(raw)
                        usage = envelope.get('usage') or {}
                        choice = envelope['choices'][0]
                        if choice.get('finish_reason') == 'length':
                            status = 'split' if split_truncated(db, chunk, cfg) else 'needs_split'
                            error = 'Output truncated; parent output was not accepted'
                        elif choice.get('finish_reason') != 'stop':
                            raise ValueError(f'Unexpected finish_reason: {choice.get("finish_reason")}')
                        else:
                            scenes = parse_scenes(choice['message']['content'])
                            write_json(run / f'responses/{aid:08d}.parsed.json', {'scenes': scenes})
                            status = 'success'
                    except APIError as exc:
                        error, retryable, retry_after = str(exc), exc.retryable, exc.retry_after
                        if not retryable:
                            stop = True
                    except (ValueError, KeyError, IndexError, TypeError) as exc:
                        error = f'Invalid response: {exc}'
                    if status == 'failed' and retryable and tries[cid] < api['attempts_per_invocation']:
                        status = 'pending'
                        due[cid] = time.monotonic() + max(retry_after, min(60, api['retry_base_seconds'] * 2 ** (tries[cid] - 1)))
                    db.execute('UPDATE attempts SET finished=?,status=?,raw_path=?,error=?,usage=? WHERE id=?',
                               (now(), status, raw_path, error, encode(usage), aid))
                    db.execute('UPDATE chunks SET status=?,error=? WHERE id=?', (status, error, cid))
                    db.commit()
                    print(f'{cid[:12]} {status}' + (f' ({error})' if error else ''), flush=True)
        print(json.dumps(status_report(db), ensure_ascii=False, indent=2))
        execution.update(finished=now(), status='stopped' if stop else 'finished',
                         report=status_report(db))
        write_json(execution_path, execution)
        if stop:
            raise ValueError('Non-retryable API error; stopped scheduling requests (see state.sqlite3)')
        unsuccessful = [cid for cid in scheduled if db.execute(
            'SELECT status FROM chunks WHERE id=?', (cid,)).fetchone()[0] in ('failed', 'needs_split')]
        if unsuccessful:
            raise ValueError(f'{len(unsuccessful)} chunks failed or still need splitting; inspect status before retrying')


def status_report(db):
    states = dict(db.execute('SELECT status,count(*) FROM chunks GROUP BY status').fetchall())
    usage = Counter()
    for row in db.execute('SELECT usage FROM attempts WHERE usage IS NOT NULL'):
        for key, value in json.loads(row['usage']).items():
            if type(value) is int:
                usage[key] += value
    works = defaultdict(lambda: {'chunks': Counter(), 'segments': 0})
    for row in db.execute('SELECT s.source,s.split,s.work_id,s.id,c.status,count(*) AS n '
                          'FROM segments s JOIN chunks c ON c.segment_id=s.id '
                          'GROUP BY s.id,c.status'):
        works[(row['source'], row['split'], row['work_id'])]['chunks'][row['status']] += row['n']
    coverage = defaultdict(Counter)
    for (source, split, _), work in works.items():
        counts = work['chunks']
        bucket = coverage[f'{source}.{split}']
        bucket['total_works'] += 1
        bucket['complete_works'] += int(set(counts) <= {'success', 'split'})
        bucket['unstarted_works'] += int(set(counts) == {'pending'})
        bucket['failed_works'] += int(bool(set(counts) & {'failed', 'needs_split'}))
    return {'chunk_status': states, 'complete': bool(states) and set(states) <= {'success', 'split'},
            'work_coverage': {key: dict(value) for key, value in coverage.items()},
            'attempts': db.execute('SELECT count(*) FROM attempts').fetchone()[0], 'usage': dict(usage)}


def source_spans(records, start, end):
    return [{'record_id': r['id'], 'start': max(start, r['start']) - r['start'],
             'end': min(end, r['end']) - r['start']}
            for r in records if r['start'] < end and start < r['end']]


def export(args):
    run = args.run.resolve()
    with locked(run), connect(run) as db:
        manifest, _ = load_run(run)
        # Version exports instead of overwriting an earlier reviewed artifact.
        export_root = run / 'exports'
        export_root.mkdir(exist_ok=True)
        number = 1
        while (export_root / f'{number:03d}').exists():
            number += 1
        output = export_root / f'{number:03d}'
        output.mkdir()
        counts = Counter()
        accepted = []
        with open(output / 'review.jsonl', 'w', encoding='utf-8') as review:
            def reject(value, reason):
                review.write(encode({**value, 'review_reason': reason}) + '\n')
                counts[f'review.{reason}'] += 1

            for segment in db.execute('SELECT * FROM segments ORDER BY source,work_id,id'):
                records = json.loads(segment['records'])
                candidates = []
                for row in db.execute("SELECT * FROM chunks WHERE segment_id=? AND status='success' ORDER BY start,end", (segment['id'],)):
                    attempt = db.execute("SELECT * FROM attempts WHERE chunk_id=? AND status='success' ORDER BY id DESC LIMIT 1", (row['id'],)).fetchone()
                    raw = read_json(run / attempt['raw_path'])
                    scenes = parse_scenes(raw['choices'][0]['message']['content'])
                    counts[f'{segment["source"]}.{segment["split"]}.processed_chunks'] += 1
                    previous_end = -1
                    for scene_index, scene in enumerate(scenes):
                        item = {'source': segment['source'], 'work_id': segment['work_id'],
                                'work_group': segment['work_group'], 'split': segment['split'],
                                'title': segment['title'], 'segment_id': segment['id'],
                                'chunk_id': row['id'], 'scene_index': scene_index, **scene}
                        try:
                            spans = locate_turns(segment['text'][row['start']:row['end']], scene['turns'])
                        except ValueError as exc:
                            reject(item, str(exc))
                            continue
                        spans = [(s + row['start'], e + row['start']) for s, e in spans]
                        item['turn_source_spans'] = [source_spans(records, s, e) for s, e in spans]
                        item['segment_spans'] = spans
                        if spans[0][0] < previous_end:
                            reject(item, 'scene_order_or_overlap')
                            continue
                        previous_end = spans[-1][1]
                        margin = manifest['config']['boundary_margin_chars']
                        boundary = ((row['start'] > 0 and spans[0][0] - row['start'] <= margin) or
                                    (row['end'] < len(segment['text']) and row['end'] - spans[-1][1] <= margin))
                        if boundary:
                            reject(item, 'chunk_boundary')
                            continue
                        candidates.append(item)
                # Preserve conflicting/partial-overlap extractions for review; never guess a merge.
                unique = {}
                for item in candidates:
                    key = encode([item['segment_spans'], item['turns']])
                    if key in unique:
                        original = unique[key]
                        if any(original[k] != item[k] for k in ('context_dependence', 'extraction_confidence')):
                            original['context_dependence'] = max(original['context_dependence'], item['context_dependence'])
                            original['extraction_confidence'] = min(original['extraction_confidence'], item['extraction_confidence'])
                            original['score_aggregation'] = 'max_context_min_confidence'
                        original.setdefault('duplicate_chunk_ids', []).append(item['chunk_id'])
                        counts['exact_duplicates_removed'] += 1
                    else:
                        unique[key] = item
                items = sorted(unique.values(), key=lambda i: i['segment_spans'][0][0])
                conflicts = set()
                for i, item in enumerate(items):
                    for j in range(i + 1, len(items)):
                        if items[j]['segment_spans'][0][0] >= item['segment_spans'][-1][1]:
                            break
                        conflicts.update((i, j))
                for i, item in enumerate(items):
                    if i in conflicts:
                        reject(item, 'partial_overlap_or_conflicting_extraction')
                    else:
                        item['scene_id'] = digest(encode([segment['id'], item['segment_spans'], item['turns']]))
                        item['record_ids'] = list(dict.fromkeys(s['record_id'] for spans in item['turn_source_spans'] for s in spans))
                        accepted.append(item)
                        counts[f'{segment["source"]}.{segment["split"]}.scenes'] += 1
                        counts[f'{segment["source"]}.{segment["split"]}.turns'] += len(item['turns'])
                        counts[f'context_dependence.{item["context_dependence"]}'] += 1
                        counts[f'extraction_confidence.{item["extraction_confidence"]}'] += 1
        with open(output / 'dialogues.jsonl', 'w', encoding='utf-8') as f:
            for item in accepted:
                f.write(encode(item) + '\n')
        # Full source metadata, including revision/license references, remains available alongside offsets.
        with open(output / 'provenance.jsonl', 'w', encoding='utf-8') as f:
            for segment in db.execute('SELECT id,records FROM segments ORDER BY id'):
                f.write(encode({'segment_id': segment['id'], 'records': json.loads(segment['records'])}) + '\n')
        report = {**status_report(db), 'counts': dict(counts), 'exported': now(),
                  'settings_sha256': manifest['settings_sha256'],
                  'prompt_sha256': manifest['prompt_sha256'],
                  'export_script_sha256': file_hash(__file__),
                  'file_sha256': {p.name: file_hash(p) for p in output.glob('*.jsonl')}}
        write_json(output / 'report.json', report)
        print(json.dumps({'output': str(output), **report}, ensure_ascii=False, indent=2))


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    commands = parser.add_subparsers(dest='command', required=True)
    prep = commands.add_parser('prepare', help='Freeze local input chunks; no API access')
    prep.add_argument('--config', type=Path, default=DEFAULT_CONFIG)
    prep.add_argument('--run', type=Path, required=True, help='New directory')
    prep.add_argument('--limit-works-per-source', type=int)
    ext = commands.add_parser('extract', help='Call the configured provider; resumes successful chunks')
    ext.add_argument('--run', type=Path, required=True)
    ext.add_argument('--max-chunks', type=int, help='Cap distinct chunks scheduled this invocation (includes split children)')
    ext.add_argument('--retry-failed', action='store_true')
    ext.add_argument('--workers', type=int, help='Runtime concurrency override; recorded in executions/')
    exp = commands.add_parser('export', help='Validate and export to a new numbered directory')
    exp.add_argument('--run', type=Path, required=True)
    stat = commands.add_parser('status')
    stat.add_argument('--run', type=Path, required=True)
    args = parser.parse_args()
    try:
        if args.command == 'prepare':
            prepare(args)
        elif args.command == 'extract':
            extract(args)
        elif args.command == 'export':
            export(args)
        else:
            with locked(args.run), connect(args.run) as db:
                load_run(args.run)
                print(json.dumps(status_report(db), ensure_ascii=False, indent=2))
    except (ValueError, OSError, sqlite3.Error) as exc:
        parser.exit(1, f'Error: {exc}\n')


if __name__ == '__main__':
    main()