Coverage for rdgai/main.py: 54.27%

234 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-24 23:53 +0000

1from pathlib import Path 

2import typer 

3from rich.console import Console 

4import pandas as pd 

5 

6from .apparatus import Doc 

7from .export import export_variants_to_excel, import_classifications_from_dataframe 

8 

9console = Console() 

10error_console = Console(stderr=True, style="bold red") 

11 

12 

13app = typer.Typer(pretty_exceptions_enable=False) 

14 

15 

16 

17def get_output_path(doc:Path, output:Path, inplace:bool) -> Path: 

18 """ Checks if the output path should be replaced with the input doc. """ 

19 if output and inplace: 

20 raise typer.BadParameter("You cannot use both an output path and --inplace/-i at the same time.") 

21 if not output and not inplace: 

22 raise typer.BadParameter("You must provide either an output path or use --inplace/-i.") 

23 

24 if inplace: 

25 output = doc 

26 

27 if isinstance(output, Doc): 

28 output = output.path 

29 

30 assert isinstance(output, Path), f"Expected Path, got {type(output)}" 

31 

32 return output 

33 

34 

35@app.command() 

36def classified_pairs( 

37 doc:Path=typer.Argument(..., help="The path to the TEI XML document with the classifications."), 

38): 

39 """ Print classified pairs in a document. """ 

40 doc = Doc(doc) 

41 doc.print_classified_pairs(console) 

42 

43 

44@app.command() 

45def evaluate( 

46 doc:Path=typer.Argument(..., help="The TEI XML document with human labels and a sample of example and test units. It is not modified."), 

47 model:str=typer.Option("anthropic:claude-opus-5-5", help="The model, as a pydantic-ai model name."), 

48 output_dir:Path=typer.Option(..., help="Where to write the working copy, the revision log and report.html / report.json."), 

49 rounds:int=typer.Option(3, help="Rounds of category review after the draft (0: draft only)."), 

50 concurrency:int=typer.Option(4, help="Units drafted at the same time."), 

51 effort:str=typer.Option(None, help="Effort level for Anthropic models."), 

52 ignore_types:list[str]=typer.Option(["defective"], "--ignore-type", help="Readings of this @type are not classified (repeatable)."), 

53 fold:int=typer.Option(None, help="Cross-validation: evaluate this fold (1-based) of the example units instead of the test units. The test units are hidden entirely."), 

54 folds:int=typer.Option(5, help="Cross-validation: number of folds."), 

55 seed:int=typer.Option(0, help="Cross-validation: seed for splitting the example units into folds."), 

56 folds_file:Path=typer.Option(None, help="Cross-validation: where the folds are saved and reused (default: <output-dir>/../folds.yaml)."), 

57 expert_model:str=typer.Option(None, help="A stronger model for the pairs the draft model is unsure about (e.g. anthropic:claude-opus-5-5)."), 

58 batch:bool=typer.Option(False, help="Draft through Anthropic Message Batches (half price; results within hours)."), 

59 poll_interval:float=typer.Option(60.0, help="With --batch: seconds between checks on the batch."), 

60 expert_mode:str=typer.Option("after", help="'after': escalate the uncertain pairs after the draft; 'tool': let the draft model ask the expert while it works."), 

61 fold_pool:str=typer.Option("example", help="Cross-validation: 'example' (folds over the example units; the test units are hidden) or 'all' (folds over every sample unit, stratified by size)."), 

62): 

63 """ 

64 Evaluates the pipeline on the sample's test units: runs it on a copy with the test units' labels removed, then 

65 compares the draft and the reviewed predictions with the human labels (per-category precision, recall, F1 and 

66 the confusion matrix). 

67 """ 

68 from .annotation import AnnotationError 

69 from .evaluate import evaluate as evaluate_fn 

70 try: 

71 report = evaluate_fn(doc, model, output_dir, rounds=rounds, concurrency=concurrency, effort=effort, ignore_types=ignore_types, 

72 fold=fold, folds=folds, seed=seed, folds_path=folds_file, pool=fold_pool, expert=expert_model, expert_mode=expert_mode, batch=batch, poll_interval=poll_interval) 

73 except AnnotationError as error: 

74 error_console.print(str(error)) 

75 raise typer.Exit(code=1) 

76 if report.fold is not None: 

77 console.print(f"Fold {report.fold} of {report.folds} (seed {report.seed}): {report.test_units} held-out units, {len(report.hidden_units)} hidden test units.") 

78 if report.cost is not None: 

79 console.print(f"Cost: ${report.cost:.2f}") 

80 if report.escalation: 

81 escalation = report.escalation 

82 console.print(f"Expert ({escalation['model']}, {escalation['mode']}): {escalation.get('flagged', 0)} uncertain pairs, " 

83 f"{escalation.get('changed', escalation.get('calls', 0))} {'changed' if escalation['mode'] == 'after' else 'questions'}, " 

84 f"${(escalation.get('cost') or 0):.2f}") 

85 console.print(f"Draft: {report.draft.correct}/{report.draft.n} correct ({report.draft.accuracy:.1%}; per unit {report.draft.unit_accuracy:.1%}), macro F1 {report.draft.macro_f1:.1%}") 

86 if report.final: 

87 stage = "After escalation" if report.escalation.get("mode") == "after" else "After review" 

88 console.print(f"{stage}: {report.final.correct}/{report.final.n} correct ({report.final.accuracy:.1%}), macro F1 {report.final.macro_f1:.1%}") 

89 for note in report.notes: 

90 console.print(note) 

91 console.print(f"Report: {Path(output_dir) / 'report.html'}") 

92 

93 

94@app.command() 

95def clean( 

96 doc:Path=typer.Argument(..., help="The path to the TEI XML document to clean."), 

97 output:Path=typer.Argument(None, help="The path to the output TEI XML file."), 

98 inplace: bool = typer.Option(False, "--inplace", "-i", help="Overwrite the input file."), 

99): 

100 """ Cleans a TEI XML file for common errors. """ 

101 output = get_output_path(doc, output, inplace) 

102 doc = Doc(doc) 

103 doc.clean(output=output) 

104 

105 

106@app.command() 

107def export( 

108 doc:Path=typer.Argument(..., help="The path to the TEI XML document to export."), 

109 output:Path=typer.Argument(..., help="The path to the output Excel file."), 

110): 

111 """ Exports pairs of readings with classifications from a TEI document to an Excel spreadsheet. """ 

112 doc = Doc(doc) 

113 export_variants_to_excel(doc, output) 

114 

115 

116@app.command() 

117def import_classifications( 

118 doc:Path=typer.Argument(..., help="The path to the base TEI XML document to use for importing the classifications from Excel."), 

119 spreadsheet:Path=typer.Argument(..., help="The path to the Excel file to import."), 

120 output:Path=typer.Argument(None, help="The path to the output TEI XML file."), 

121 inplace: bool = typer.Option(False, "--inplace", "-i", help="Overwrite the input file."), 

122 responsible:str=typer.Option("", help="The responsible party for the classifications. By default it is the name of the spreadsheet."), 

123): 

124 """ Imports classifications from a spreadsheet into a TEI document. """ 

125 doc = Doc(doc) 

126 output = get_output_path(doc, output, inplace) 

127 

128 if spreadsheet.suffix == ".xlsx": 

129 variants_df = pd.read_excel(spreadsheet, sheet_name="Variants", keep_default_na=False) 

130 elif spreadsheet.suffix == ".csv": 

131 variants_df = pd.read_csv(spreadsheet, keep_default_na=False) 

132 

133 # TODO add responsible to TEI header 

134 responsible = responsible or spreadsheet.stem 

135 responsible = responsible.replace(" ", "_") 

136 if not responsible.startswith("#"): 

137 responsible = "#" + responsible 

138 

139 import_classifications_from_dataframe(doc, variants_df, output, responsible=responsible) 

140 

141 

142@app.command() 

143def serve_mcp( 

144 doc:Path=typer.Argument(..., help="The TEI XML document. It is modified in place when classifications are set."), 

145 transport:str=typer.Option("stdio", help="Transport: 'stdio' or 'http' (streamable HTTP)."), 

146 host:str=typer.Option("127.0.0.1", help="Host for the HTTP transport."), 

147 port:int=typer.Option(8000, help="Port for the HTTP transport."), 

148 annotator:str=typer.Option(None, help="xml:id of the human annotator responsible for classifications set through this server, e.g. 'RT'."), 

149 annotator_name:str=typer.Option(None, help="Full name of the annotator (used in the <respStmt> added to the TEI header)."), 

150 read_only:bool=typer.Option(False, help="Disable all tools that change the file."), 

151 lock_definitions:bool=typer.Option(False, help="Disable the tools that edit the category definitions."), 

152 evaluation:bool=typer.Option(False, help="Evaluation mode: no tool reveals the labels or suggestions of the sample's test units, test units cannot be changed, and the definitions are locked."), 

153 reading_notes:bool=typer.Option(True, help="Treat text in parentheses in readings (e.g. ECM's '(cf. 24b)') as notes, not reading text."), 

154 ignore_types:list[str]=typer.Option(["defective"], "--ignore-type", help="Readings of this @type are not classified (repeatable). Defaults to defective."), 

155 sample_file:Path=typer.Option(None, help="Sidecar YAML file for the sample of units (default: <doc>.sample.yaml)."), 

156 gui_port:int=typer.Option(None, help="Also serve the annotation GUI on this port, in the same process (e.g. 8765)."), 

157 gui_host:str=typer.Option("127.0.0.1", help="Host for the annotation GUI."), 

158 gui_retry_seconds:float=typer.Option(15.0, help="If the GUI port is taken (e.g. by a second process for the same file), try it again this often, so the GUI survives either process exiting (0: never)."), 

159 group_by_prefix:str=typer.Option(None, help="Lay out the GUI's category buttons in rows by the part of the name before this separator, e.g. '_'."), 

160 compact_threshold:int=typer.Option(10, help="In the GUI, show units with more pairs than this as compact rows."), 

161): 

162 """ Serves an MCP server for querying and classifying the reading pairs in a TEI document. """ 

163 from .annotation import AnnotationStore, AnnotationError 

164 from .mcp_server import build_server 

165 

166 if not read_only and not annotator: 

167 raise typer.BadParameter("Provide --annotator (the xml:id of the person responsible) or use --read-only.") 

168 

169 try: 

170 store = AnnotationStore( 

171 doc, annotator=annotator, annotator_name=annotator_name, read_only=read_only, lock_definitions=lock_definitions, 

172 ignore_types=ignore_types, sample_path=sample_file, reading_notes=reading_notes, evaluation=evaluation, 

173 ) 

174 except AnnotationError as error: 

175 error_console.print(str(error)) 

176 raise typer.Exit(code=1) 

177 if transport not in ("stdio", "http"): 

178 raise typer.BadParameter("transport must be 'stdio' or 'http'.") 

179 server = build_server(store) 

180 if gui_port: 

181 import anyio 

182 from .gui import create_app 

183 from .gui.serve import serve_mcp_with_gui 

184 gui_app = create_app(store, group_by_prefix=group_by_prefix, compact_threshold=compact_threshold) 

185 anyio.run(lambda: serve_mcp_with_gui( 

186 server, gui_app, gui_host, gui_port, transport=transport, host=host, port=port, retry_seconds=gui_retry_seconds, 

187 )) 

188 elif transport == "stdio": 

189 server.run("stdio") 

190 else: 

191 server.run("streamable-http", host=host, port=port) 

192 

193 

194@app.command() 

195def apply_rules( 

196 doc:Path=typer.Argument(..., help="The TEI XML document."), 

197 rule:list[str]=typer.Option(None, "--rule", help="Reading type and category, e.g. orthographic=Orthography (repeatable). Replaces the rules stored in the file."), 

198 suffix:list[str]=typer.Option(None, "--suffix", help="Reading type and id suffix, e.g. orthographic=o (repeatable). Defaults: orthographic o, defective f."), 

199 dry_run:bool=typer.Option(False, "--dry-run", help="Report what would change without saving."), 

200 inplace:bool=typer.Option(False, "--inplace", "-i", help="Modify the document in place."), 

201 output:Path=typer.Option(None, "--output", "-o", help="Write the result to this file instead."), 

202 ignore_types:list[str]=typer.Option(["defective"], "--ignore-type", help="Readings of this @type are not classified (repeatable). Defaults to defective."), 

203 reading_notes:bool=typer.Option(True, help="Treat text in parentheses in readings as notes, not reading text."), 

204): 

205 """ 

206 Labels the pairs formed by typed subreadings (e.g. ECM orthographic readings 'ao', 'ao1' of reading 'a') by rule: 

207 a subreading and its parent, and two subreadings of the same parent, get the mapped category. Other pairs with a 

208 subreading (e.g. ao-b) are ordinary pairs, for an annotator or the pipeline; rule labels left on them (from the 

209 former rule 3) are removed. Human labels are never changed. Running it again changes nothing. 

210 """ 

211 import shutil 

212 from .annotation import AnnotationStore, AnnotationError 

213 from .rules import build_rules, parse_assignments 

214 

215 if not dry_run: 

216 if inplace and output: 

217 raise typer.BadParameter("Use either --inplace or --output, not both.") 

218 if not inplace and not output: 

219 raise typer.BadParameter("Give --inplace, --output FILE or --dry-run.") 

220 target = doc 

221 if output and not dry_run: 

222 output.parent.mkdir(parents=True, exist_ok=True) 

223 shutil.copy(doc, output) 

224 target = output 

225 try: 

226 store = AnnotationStore(target, ignore_types=ignore_types, reading_notes=reading_notes, check_sample=False) 

227 rules = build_rules(store.rules, parse_assignments(rule, "--rule"), parse_assignments(suffix, "--suffix")) 

228 report = store.apply_rules(rules, dry_run=dry_run) 

229 except (AnnotationError, ValueError) as error: 

230 error_console.print(str(error)) 

231 raise typer.Exit(code=1) 

232 

233 names = {1: "subreading ↔ parent", 2: "sibling subreadings"} 

234 if dry_run: 

235 typer.echo("Dry run: nothing was saved.") 

236 typer.echo("Rules: " + ", ".join(f"{item.reading_type} → {item.category} (suffix '{item.suffix}')" for item in report.rules)) 

237 for count in report.counts: 

238 line = f"Rule {count.rule} ({names[count.rule]}): {count.covered} pairs: {count.written} written, {count.unchanged} unchanged" 

239 if count.human: 

240 line += f", {count.human} kept (labelled by a human)" 

241 typer.echo(line) 

242 if report.removed: 

243 typer.echo(f"Leftover rule labels removed (pairs no rule covers): {report.removed}") 

244 if report.descriptions_updated: 

245 typer.echo("Rule descriptions updated: " + ", ".join(report.descriptions_updated)) 

246 if report.unresolved: 

247 typer.echo("Unresolved parents: " + "; ".join(f"{item.unit_id} {item.reading}" for item in report.unresolved)) 

248 if report.nested: 

249 typer.echo("Nested subreadings: " + "; ".join(f"{item.unit_id} {item.reading} (of {item.parent})" for item in report.nested)) 

250 if report.conflicts: 

251 typer.echo(f"Conflicts (human labels kept): {len(report.conflicts)}") 

252 for conflict in report.conflicts: 

253 typer.echo(f" {conflict.unit_id} {conflict.active} → {conflict.passive}: {conflict.label} (rule {conflict.rule} gives {conflict.rule_label})") 

254 if not dry_run: 

255 typer.echo(f"Saved to {target}") 

256 

257 

258@app.command() 

259def annotate( 

260 doc:Path=typer.Argument(..., help="The TEI XML document. It is modified in place when classifications are saved."), 

261 port:int=typer.Option(8765, help="Port for the GUI."), 

262 host:str=typer.Option("127.0.0.1", help="Host for the GUI."), 

263 annotator:str=typer.Option(None, help="xml:id of the human annotator responsible for the labels saved, e.g. 'RT'."), 

264 annotator_name:str=typer.Option(None, help="Full name of the annotator (used in the <respStmt> added to the TEI header)."), 

265 read_only:bool=typer.Option(False, help="View only: no labels can be saved."), 

266 evaluation:bool=typer.Option(False, help="Evaluation mode: the labels and suggestions of the sample's test units are not shown, and test units cannot be changed."), 

267 reading_notes:bool=typer.Option(True, help="Treat text in parentheses in readings (e.g. ECM's '(cf. 24b)') as notes, not reading text."), 

268 ignore_types:list[str]=typer.Option(["defective"], "--ignore-type", help="Readings of this @type are not classified (repeatable). Defaults to defective."), 

269 sample_file:Path=typer.Option(None, help="Sidecar YAML file for the sample of units (default: <doc>.sample.yaml)."), 

270 group_by_prefix:str=typer.Option(None, help="Lay out the category buttons in rows by the part of the name before this separator, e.g. '_'."), 

271 compact_threshold:int=typer.Option(10, help="Show units with more pairs than this as compact rows."), 

272 open_browser:bool=typer.Option(False, "--open", help="Open the GUI in a web browser."), 

273): 

274 """ Runs the annotation GUI on its own (use `serve-mcp --gui-port` to run it inside the MCP server instead). """ 

275 from .annotation import AnnotationStore, AnnotationError 

276 from .gui import create_app 

277 from .gui.serve import bind, gui_server 

278 

279 if not read_only and not annotator: 

280 raise typer.BadParameter("Provide --annotator (the xml:id of the person responsible) or use --read-only.") 

281 try: 

282 store = AnnotationStore( 

283 doc, annotator=annotator, annotator_name=annotator_name, read_only=read_only, 

284 ignore_types=ignore_types, sample_path=sample_file, reading_notes=reading_notes, evaluation=evaluation, 

285 ) 

286 except AnnotationError as error: 

287 error_console.print(str(error)) 

288 raise typer.Exit(code=1) 

289 

290 sock = bind(host, port) 

291 if sock is None: 

292 raise typer.Exit(code=1) 

293 url = f"http://{host}:{port}/" 

294 console.print(f"Annotation GUI for {doc} at {url}") 

295 if open_browser: 

296 import webbrowser 

297 webbrowser.open(url) 

298 import anyio 

299 anyio.run(lambda: gui_server(create_app(store, group_by_prefix=group_by_prefix, compact_threshold=compact_threshold), host, port).serve([sock])) 

300 

301 

302@app.command() 

303def sample( 

304 doc:Path=typer.Argument(..., help="The TEI XML document."), 

305 size:int=typer.Option(..., "--size", "-n", help="Number of units to sample."), 

306 seed:int=typer.Option(..., help="Random seed. The same seed and settings give the same sample."), 

307 test_fraction:float=typer.Option(0.5, help="Fraction of the sampled units held out as test units."), 

308 max_pairs:int=typer.Option(None, help="Exclude units with more pairs than this."), 

309 ignore_types:list[str]=typer.Option(["defective"], "--ignore-type", help="Readings of this @type are not classified (repeatable). Defaults to defective."), 

310 sample_file:Path=typer.Option(None, help="Sidecar YAML file to write (default: <doc>.sample.yaml)."), 

311 overwrite:bool=typer.Option(False, help="Replace an existing sample file."), 

312): 

313 """ Draws a reproducible random sample of variation units, split into example and test units. """ 

314 from .annotation import AnnotationStore, AnnotationError 

315 

316 try: 

317 store = AnnotationStore(doc, ignore_types=ignore_types, sample_path=sample_file, check_sample=not overwrite) 

318 info = store.draw_sample(size=size, seed=seed, test_fraction=test_fraction, max_pairs=max_pairs, overwrite=overwrite) 

319 except AnnotationError as error: 

320 error_console.print(str(error)) 

321 raise typer.Exit(code=1) 

322 

323 console.print(f"Sampled {info.size} of {info.eligible_count} eligible units (seed {info.seed}) -> {info.path}") 

324 for progress in info.progress: 

325 console.print(f" {progress.role}: {progress.units} units, {progress.pairs} pairs") 

326 

327 

328def open_store(doc:Path, ignore_types:list[str], sample_file:Path|None, reading_notes:bool=True, **kwargs): 

329 from .annotation import AnnotationStore, AnnotationError 

330 try: 

331 return AnnotationStore(doc, ignore_types=ignore_types, sample_path=sample_file, reading_notes=reading_notes, **kwargs) 

332 except AnnotationError as error: 

333 error_console.print(str(error)) 

334 raise typer.Exit(code=1) 

335 

336 

337@app.command() 

338def estimate( 

339 doc:Path=typer.Argument(..., help="The TEI XML document."), 

340 model:str=typer.Option("anthropic:claude-opus-5-5", help="The model, as a pydantic-ai model name (e.g. anthropic:claude-opus-5-5, openai:gpt-5)."), 

341 unit:list[str]=typer.Option(None, "--unit", help="Only these units (repeatable)."), 

342 ignore_types:list[str]=typer.Option(["defective"], "--ignore-type", help="Readings of this @type are not classified (repeatable)."), 

343 sample_file:Path=typer.Option(None, help="Sidecar YAML file for the sample (default: <doc>.sample.yaml)."), 

344): 

345 """ Estimates the tokens and cost of drafting the pairs still to classify, without calling any model. """ 

346 from .pipeline import estimate as estimate_fn 

347 store = open_store(doc, ignore_types, sample_file, read_only=True) 

348 result = estimate_fn(store, model, unit_ids=unit or None) 

349 console.print(f"{result.pairs} pairs to classify in {result.units} units ({result.requests} requests) with {result.model}") 

350 console.print(f"About {result.input_tokens:,} input tokens ({result.cache_read_tokens:,} from the prompt cache) and {result.output_tokens:,} output tokens") 

351 if result.cost is None: 

352 console.print("Cost: unknown for this model") 

353 else: 

354 console.print(f"Estimated cost: ${result.cost:,.2f} (rough: calibrate with a small run, e.g. rdgai draft --limit-units 20)") 

355 if model.startswith("anthropic:"): 

356 console.print(f"With --batch (Message Batches, half price): about ${result.cost / 2:,.2f}") 

357 

358 

359@app.command() 

360def draft( 

361 doc:Path=typer.Argument(..., help="The TEI XML document. Labels are written to it as the pipeline's (resp='#rdgai')."), 

362 model:str=typer.Option("anthropic:claude-opus-5-5", help="The model, as a pydantic-ai model name (e.g. anthropic:claude-opus-5-5, openai:gpt-5)."), 

363 unit:list[str]=typer.Option(None, "--unit", help="Only these units (repeatable)."), 

364 limit_units:int=typer.Option(None, help="Classify at most this many units (e.g. to calibrate the cost estimate)."), 

365 concurrency:int=typer.Option(4, help="Units classified at the same time."), 

366 effort:str=typer.Option(None, help="Effort level for Anthropic models (low, medium, high, xhigh, max)."), 

367 ignore_types:list[str]=typer.Option(["defective"], "--ignore-type", help="Readings of this @type are not classified (repeatable)."), 

368 sample_file:Path=typer.Option(None, help="Sidecar YAML file for the sample (default: <doc>.sample.yaml)."), 

369 batch:bool=typer.Option(False, help="Send the requests as Anthropic Message Batches: half the price; results within hours (Anthropic models only)."), 

370 poll_interval:float=typer.Option(60.0, help="With --batch: seconds between checks on the batch."), 

371 state_file:Path=typer.Option(None, help="With --batch: where the batch state is kept, so an interrupted run resumes without paying again (default: <doc>.batch-state.json)."), 

372): 

373 """ 

374 Draft pass: classifies the pairs still to classify (not those covered by subreading rules), unit by unit. 

375 Agents read through the rdgai MCP server and give a checked decision per pair. Resumable: run it again to continue. 

376 """ 

377 from .pipeline import draft as draft_fn 

378 store = open_store(doc, ignore_types, sample_file) 

379 if batch: 

380 from .batch import draft_batch 

381 report = draft_batch(store, model, unit_ids=unit or None, limit_units=limit_units, poll_interval=poll_interval, 

382 state_path=state_file or doc.with_name(f"{doc.stem}.batch-state.json"), 

383 progress=lambda message: console.print(f" {message}")) 

384 else: 

385 report = draft_fn( 

386 store, model, unit_ids=unit or None, limit_units=limit_units, concurrency=concurrency, effort=effort, 

387 progress=lambda app: console.print(f" {app}"), 

388 ) 

389 console.print(f"Run {report.run_id}: {report.pairs_written} pairs written in {report.units_done} units; {report.pairs_skipped} skipped (labelled meanwhile)") 

390 usage = report.usage 

391 console.print(f"{usage['requests']} requests, {usage['input_tokens']:,} input tokens ({usage['cache_read_tokens']:,} cached), {usage['output_tokens']:,} output tokens" 

392 + (f", ${report.cost:,.2f}" if report.cost is not None else "")) 

393 for error in report.errors: 

394 error_console.print(error) 

395 

396 

397def print_usage(report): 

398 usage = report.usage 

399 console.print(f"{usage['requests']} requests, {usage['input_tokens']:,} input tokens ({usage['cache_read_tokens']:,} cached), {usage['output_tokens']:,} output tokens" 

400 + (f", ${report.cost:,.2f}" if report.cost is not None else "")) 

401 for error in report.errors: 

402 error_console.print(error) 

403 

404 

405@app.command() 

406def review( 

407 doc:Path=typer.Argument(..., help="The TEI XML document."), 

408 model:str=typer.Option("anthropic:claude-opus-5-5", help="The model, as a pydantic-ai model name."), 

409 rounds:int=typer.Option(3, help="At most this many rounds of review (stops early when a round changes nothing)."), 

410 category:list[str]=typer.Option(None, "--category", help="Only review these categories (repeatable)."), 

411 unit:list[str]=typer.Option(None, "--unit", help="Only review labels in these units (repeatable)."), 

412 effort:str=typer.Option(None, help="Effort level for Anthropic models."), 

413 log:Path=typer.Option(None, help="Revision log (JSON lines; default <doc>.revisions.jsonl)."), 

414 ignore_types:list[str]=typer.Option(["defective"], "--ignore-type", help="Readings of this @type are not classified (repeatable)."), 

415 sample_file:Path=typer.Option(None, help="Sidecar YAML file for the sample (default: <doc>.sample.yaml)."), 

416): 

417 """ Reviews the pipeline's labels one category at a time and applies the revisions (human labels are never changed). """ 

418 from .pipeline import review as review_fn 

419 store = open_store(doc, ignore_types, sample_file) 

420 report = review_fn(store, model, categories=category or None, rounds=rounds, unit_ids=unit or None, effort=effort, log_path=log, 

421 progress=lambda round_number, name: console.print(f" round {round_number}: {name}")) 

422 applied = sum(entry.status == "applied" for entry in report.revisions) 

423 console.print(f"Run {report.run_id}: {report.rounds_run} rounds, {applied} revisions applied, {len(report.revisions) - applied} skipped") 

424 for note in report.notes: 

425 console.print(f"Note: {note}") 

426 print_usage(report) 

427 

428 

429@app.command() 

430def run( 

431 doc:Path=typer.Argument(..., help="The TEI XML document."), 

432 model:str=typer.Option("anthropic:claude-opus-5-5", help="The model, as a pydantic-ai model name."), 

433 rounds:int=typer.Option(3, help="Rounds of category review after the draft (0: draft only)."), 

434 limit_units:int=typer.Option(None, help="Draft at most this many units."), 

435 concurrency:int=typer.Option(4, help="Units drafted at the same time."), 

436 effort:str=typer.Option(None, help="Effort level for Anthropic models."), 

437 ignore_types:list[str]=typer.Option(["defective"], "--ignore-type", help="Readings of this @type are not classified (repeatable)."), 

438 sample_file:Path=typer.Option(None, help="Sidecar YAML file for the sample (default: <doc>.sample.yaml)."), 

439): 

440 """ The full pipeline: subreading rules (if configured), the draft pass, then category review. Resumable. """ 

441 from .pipeline import draft as draft_fn, review as review_fn 

442 store = open_store(doc, ignore_types, sample_file) 

443 if store.rules: 

444 store.apply_rules() 

445 report = draft_fn(store, model, limit_units=limit_units, concurrency=concurrency, effort=effort, 

446 progress=lambda app: console.print(f" {app}")) 

447 console.print(f"Draft {report.run_id}: {report.pairs_written} pairs written in {report.units_done} units") 

448 print_usage(report) 

449 if rounds > 0: 

450 reviewed = review_fn(store, model, rounds=rounds, effort=effort, 

451 progress=lambda round_number, name: console.print(f" round {round_number}: {name}")) 

452 applied = sum(entry.status == "applied" for entry in reviewed.revisions) 

453 console.print(f"Review {reviewed.run_id}: {reviewed.rounds_run} rounds, {applied} revisions applied") 

454 print_usage(reviewed) 

455 if store.rules: 

456 store.apply_rules()