#!/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 = "" # Set your DeepSeek API key here. VERSION = 1 OPENAI_API_KEY = '' # 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()