Coverage for rdgai/gui/__init__.py: 98.53%

339 statements  

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

1""" 

2A browser GUI for annotating and reviewing transcriptional-change classifications. 

3 

4It is a small Starlette app over the same ``AnnotationStore`` as the MCP server, so it can run inside the MCP 

5server's process (``rdgai serve-mcp --gui-port``) or on its own (``rdgai annotate``). Everything about the 

6categories comes from the TEI ``<interpGrp type="transcriptional">``; nothing is specific to one corpus. 

7""" 

8import re 

9from pathlib import Path 

10 

11from pydantic import BaseModel 

12from starlette.applications import Starlette 

13from starlette.middleware import Middleware 

14from starlette.concurrency import run_in_threadpool 

15from starlette.requests import Request 

16from starlette.responses import FileResponse, JSONResponse 

17from starlette.routing import Mount, Route 

18from starlette.staticfiles import StaticFiles 

19 

20from ..annotation import ( 

21 AnnotationError, 

22 AnnotationStore, 

23 Category, 

24 CERTAINTY_VALUES, 

25 ConflictError, 

26 DefinitionsLockedError, 

27 ReadOnlyError, 

28 UnitNotFoundError, 

29) 

30 

31from . import views 

32from .display import display_path, load_display, save_display, initials 

33 

34STATIC = Path(__file__).parent / "static" 

35INVERSE_PREFIX = re.compile(r"^Inverse of (\S+) → (\S+):\s*") 

36 

37 

38def display_justification(text:str) -> str: 

39 """ Labels and suggestions saved for the reverse direction start 'Inverse of a → b: '; the GUI does not show that. """ 

40 return INVERSE_PREFIX.sub("", text or "") 

41 

42# Keys for the category buttons, in button order: 1-9, 0, then shift+1 ... shift+0. 

43KEYS = [str(digit) for digit in range(1, 10)] + ["0"] + [f"shift+{digit}" for digit in [*range(1, 10), 0]] 

44 

45 

46class Button(BaseModel): 

47 name: str 

48 short: str = "" 

49 description: str 

50 inverse: str 

51 group: str 

52 row: int 

53 column: int 

54 key: str | None 

55 

56 

57def short_labels(names:list[str]) -> dict[str, str]: 

58 """ 

59 Short, distinct labels for category buttons in compact rows: the first letters of each part of the name 

60 (e.g. Minor_Omission -> 'Min·Omi', Orthography -> 'Orth'), lengthened where two would be the same. 

61 """ 

62 def parts(name:str) -> list[str]: 

63 return [part for part in re.split(r"[_\-\s.]+", name) if part] or [name] 

64 

65 def make(name:str, length:int) -> str: 

66 name_parts = parts(name) 

67 if len(name_parts) == 1: 

68 return name_parts[0][:length] 

69 return "·".join(part[:length] for part in name_parts) 

70 

71 lengths = {name: (4 if len(parts(name)) == 1 else 3) for name in names} 

72 longest = max((len(name) for name in names), default=0) 

73 while True: 

74 labels = {name: make(name, lengths[name]) for name in names} 

75 seen = {} 

76 for name, label in labels.items(): 

77 seen.setdefault(label, []).append(name) 

78 clashes = [group for group in seen.values() if len(group) > 1] 

79 if not clashes or all(lengths[name] > longest for group in clashes for name in group): 

80 return labels 

81 for group in clashes: 

82 for name in group: 

83 lengths[name] += 1 

84 

85 

86def button_layout(categories:list[Category], group_by_prefix:str|None=None) -> list[Button]: 

87 """ 

88 Lays out one button per category in a grid with fixed positions. 

89 

90 Rows come from a grouping hint: the <interp>'s @type/@n (Category.group) if any category has one, otherwise 

91 the part of the name before ``group_by_prefix`` (e.g. 'Minor' in 'Minor_Omission'). Rows are in order of first 

92 appearance. When grouping by prefix, columns are aligned by the rest of the name, so that e.g. Minor_Omission 

93 sits above Major_Omission. Without a hint, all buttons are in one row in document order. 

94 Keys are assigned in row-major order. 

95 """ 

96 use_types = any(category.group for category in categories) 

97 placements = [] 

98 for category in categories: 

99 if use_types: 

100 group, suffix = category.group, None 

101 elif group_by_prefix and group_by_prefix in category.name: 

102 group, suffix = category.name.split(group_by_prefix, 1) 

103 else: 

104 group, suffix = "", None 

105 placements.append((category, group, suffix)) 

106 

107 rows = list(dict.fromkeys(group for _, group, _ in placements)) 

108 suffixes = list(dict.fromkeys(suffix for _, group, suffix in placements if suffix is not None and group)) 

109 next_column = {group: 0 for group in rows} 

110 

111 cells = [] 

112 for category, group, suffix in placements: 

113 if suffix is not None and group: 

114 column = suffixes.index(suffix) 

115 else: 

116 column = next_column[group] 

117 next_column[group] += 1 

118 cells.append((rows.index(group), column, category, group)) 

119 

120 cells.sort(key=lambda cell: (cell[0], cell[1])) 

121 shorts = short_labels([category.name for category in categories]) 

122 return [ 

123 Button( 

124 name=category.name, 

125 short=shorts[category.name], 

126 description=category.description, 

127 inverse=category.inverse, 

128 group=group, 

129 row=row, 

130 column=column, 

131 key=KEYS[index] if index < len(KEYS) else None, 

132 ) 

133 for index, (row, column, category, group) in enumerate(cells) 

134 ] 

135 

136 

137def pair_key(active:str, passive:str) -> str: 

138 return f"{active}|{passive}" 

139 

140 

141def parse_pairs(data) -> list[tuple[str, str]]: 

142 pairs = data.get("pairs") or [] 

143 return [(str(pair[0]), str(pair[1])) for pair in pairs] 

144 

145 

146def parse_expected(data) -> dict: 

147 """ {"a|b": category or null} -> {("a", "b"): category or None}; pairs not listed are not checked. """ 

148 expected = {} 

149 for key, value in (data.get("expected") or {}).items(): 

150 active, _, passive = key.partition("|") 

151 expected[(active, passive)] = value if value is None else str(value) 

152 return expected 

153 

154 

155def error_response(error:AnnotationError) -> JSONResponse: 

156 if isinstance(error, ConflictError): 

157 current = {pair_key(*key): value for key, value in error.current.items()} 

158 return JSONResponse({"error": str(error), "current": current}, status_code=409) 

159 if isinstance(error, (ReadOnlyError, DefinitionsLockedError)): 

160 return JSONResponse({"error": str(error)}, status_code=403) 

161 if isinstance(error, UnitNotFoundError): 

162 return JSONResponse({"error": str(error)}, status_code=404) 

163 return JSONResponse({"error": str(error)}, status_code=400) 

164 

165 

166class CacheControl: 

167 """ 

168 The API is never cached (another process, e.g. Claude through MCP, may change the file at any time); 

169 the page and its scripts are revalidated on every load. 

170 """ 

171 def __init__(self, app): 

172 self.app = app 

173 

174 async def __call__(self, scope, receive, send): 

175 if scope["type"] != "http": 

176 return await self.app(scope, receive, send) 

177 value = b"no-store" if scope["path"].startswith("/api/") else b"no-cache" 

178 

179 async def send_with_header(message): 

180 if message["type"] == "http.response.start": 

181 headers = [(name, item) for name, item in message.get("headers", []) if name.lower() != b"cache-control"] 

182 message = {**message, "headers": headers + [(b"cache-control", value)]} 

183 await send(message) 

184 

185 await self.app(scope, receive, send_with_header) 

186 

187 

188def file_version(*paths:Path) -> str: 

189 """ A token that changes whenever any of the files changes (rdgai replaces files atomically, so the inode changes). """ 

190 parts = [] 

191 for path in paths: 

192 try: 

193 stat = path.stat() 

194 parts.append(f"{stat.st_ino}-{stat.st_mtime_ns}-{stat.st_size}") 

195 except FileNotFoundError: 

196 parts.append("none") 

197 return "|".join(parts) 

198 

199 

200def create_app(store:AnnotationStore, group_by_prefix:str|None=None, compact_threshold:int=10) -> Starlette: 

201 """ Builds the GUI app over a store (which may be shared with an MCP server in the same process). """ 

202 

203 def queue_filters(request:Request) -> dict: 

204 params = request.query_params 

205 default_sample = "sampled" if store.load_sample() else "all" 

206 return dict( 

207 sample=params.get("sample") or default_sample, 

208 status=params.get("status") or "all", 

209 verse=params.get("verse") or "", 

210 category=params.get("category") or "", 

211 cert=params.get("cert") or "", 

212 source=params.get("source") or "", 

213 disagreement="1" if (params.get("disagreement") or "").lower() in views.TRUE_VALUES else "", 

214 ) 

215 

216 def queue_apps(filters:dict): 

217 return views.filter_queue(store, filters) 

218 

219 def pair_payload(app, pair, role:str|None) -> dict: 

220 info = store.pair_info(pair) 

221 suggestions = [] 

222 for suggestion in ([] if role == "test" else store.suggestions_for(app, pair)): 

223 match = INVERSE_PREFIX.match(suggestion.justification or "") 

224 payload = suggestion.model_dump() 

225 payload["justification"] = display_justification(suggestion.justification) 

226 # text written for the other direction would read as contradicting the category shown: say which direction 

227 payload["written_for"] = [match[1], match[2]] if match else None 

228 suggestions.append(payload) 

229 if info.provenance is not None: 

230 info.provenance.justification = display_justification(info.provenance.justification) 

231 # the reason box holds the annotator's own reason only: it starts empty (suggestions are shown separately) 

232 reason = info.provenance.justification if info.provenance is not None else "" 

233 rule = dict(rule=info.rule) if info.rule is not None else None 

234 translations = store.translations_for(app) 

235 return dict( 

236 first=pair.active.n, 

237 second=pair.passive.n, 

238 first_text=info.active_text, 

239 second_text=info.passive_text, 

240 category=info.category, 

241 inverse_category=info.inverse_category, 

242 provenance=info.provenance.model_dump() if info.provenance else None, 

243 source=info.source, 

244 rule=rule, 

245 change=info.change.model_dump() if info.change else None, 

246 warning=info.warning, 

247 suggestions=suggestions, 

248 reason=reason, 

249 first_translation=translations.get(pair.active.n), 

250 second_translation=translations.get(pair.passive.n), 

251 ) 

252 

253 def progress(app) -> dict: 

254 pairs = store.work_pairs(app) 

255 return dict( 

256 pairs_done=sum(store.is_classified(pair) for pair in pairs), 

257 pairs_total=len(pairs), 

258 rule_pairs=len(store.rule_pairs(app)), 

259 ) 

260 

261 def next_unclassified(apps:list, current_id:str) -> str|None: 

262 ids = [str(app) for app in apps] 

263 start = ids.index(current_id) + 1 if current_id in ids else 0 

264 for offset in range(len(apps)): 

265 app = apps[(start + offset) % len(apps)] 

266 if str(app) != current_id and store.status(app) in ("unclassified", "partial"): 

267 return str(app) 

268 return None 

269 

270 def current_version() -> str: 

271 return file_version(store.path, store.sample_path, store.translations_path) 

272 

273 def version(request:Request): 

274 return JSONResponse(dict(version=current_version())) 

275 

276 async def index(request:Request): 

277 return FileResponse(STATIC / "index.html") 

278 

279 def config(request:Request): 

280 with store.lock: 

281 store.refresh() 

282 definitions = store.definitions() 

283 buttons = button_layout(definitions.categories, group_by_prefix=group_by_prefix) 

284 return JSONResponse(dict( 

285 file=store.path.name, 

286 language=definitions.language, 

287 guidance=definitions.guidance, 

288 classifier_instructions=definitions.classifier_instructions, 

289 constraints=definitions.constraints, 

290 direction_convention=definitions.direction_convention, 

291 definitions_hash=definitions.definitions_hash, 

292 buttons=[button.model_dump() for button in buttons], 

293 certainty=list(CERTAINTY_VALUES), 

294 annotator=store.annotator, 

295 annotator_name=store.annotator_full_name(), 

296 profile=profile(), 

297 title=load_display(display_path(store.path)).get("title") or None, 

298 read_only=store.read_only, 

299 definitions_editable=not store.read_only and not store.lock_definitions, 

300 evaluation=store.evaluation, 

301 compact_threshold=compact_threshold, 

302 has_sample=store.load_sample() is not None, 

303 )) 

304 

305 def queue(request:Request): 

306 try: 

307 with store.lock: 

308 store.refresh() 

309 filters = queue_filters(request) 

310 apps = queue_apps(filters) 

311 return JSONResponse(dict( 

312 filters=filters, 

313 total=len(apps), 

314 units=[store.unit_summary(app).model_dump() for app in apps], 

315 )) 

316 except AnnotationError as error: 

317 return error_response(error) 

318 

319 def sample_progress(request:Request): 

320 """ Labelled pairs and complete units per role of the sample (example, test) and in the whole file, for the sidebar's bars. """ 

321 with store.lock: 

322 store.refresh() 

323 if store.load_sample() is None: 

324 return JSONResponse(dict(sample=False, file=store.file_progress())) 

325 result = dict(sample=True, file=store.file_progress()) 

326 for role in ("example", "test"): 

327 counts = dict(pairs_done=0, pairs_total=0, units_done=0, units_total=0) 

328 for app in store.filter_units(sample=role): 

329 pairs = store.work_pairs(app) 

330 counts["pairs_done"] += sum(store.is_classified(pair) for pair in pairs) 

331 counts["pairs_total"] += len(pairs) 

332 counts["units_done"] += store.status(app) in ("classified", "nothing_to_classify") 

333 counts["units_total"] += 1 

334 result[role] = counts 

335 return JSONResponse(result) 

336 

337 def unit(request:Request): 

338 try: 

339 with store.lock: 

340 store.refresh() 

341 app = store.get_app(request.path_params["unit_id"]) 

342 unit_id = str(app) 

343 filters = queue_filters(request) 

344 apps = queue_apps(filters) 

345 ids = [str(queued) for queued in apps] 

346 role = store.sample_role(unit_id) 

347 if unit_id in ids: 

348 index = ids.index(unit_id) 

349 position = dict(index=index, total=len(ids)) 

350 prev_id = ids[index - 1] if index > 0 else None 

351 next_id = ids[index + 1] if index + 1 < len(ids) else None 

352 else: 

353 position, prev_id, next_id = None, None, (ids[0] if ids else None) 

354 detail = store.get_unit(unit_id) 

355 ordered = store.reading_ordered_pairs(app) 

356 return JSONResponse(dict( 

357 id=unit_id, 

358 verse=detail.verse, 

359 sample_role=role, 

360 status=detail.status, 

361 position=position, 

362 prev=prev_id, 

363 next=next_id, 

364 next_unclassified=next_unclassified(apps, unit_id), 

365 progress=progress(app), 

366 context=dict(before=app.text_before(), lemma=app.text(), after=app.text_after()), 

367 readings=[reading.model_dump() for reading in detail.readings], 

368 lacunose_witnesses=detail.lacunose_witnesses, 

369 translations=detail.translations, 

370 pairs=[pair_payload(app, pair, role) for pair in ordered if store.coverage_for(pair) is None], 

371 rule_pairs=[pair_payload(app, pair, role) for pair in ordered if store.coverage_for(pair) is not None], 

372 filters=filters, 

373 version=current_version(), 

374 )) 

375 except AnnotationError as error: 

376 return error_response(error) 

377 

378 def write_payload(unit_id:str, pairs:list[tuple[str, str]]) -> dict: 

379 with store.lock: 

380 app = store.get_app(unit_id) 

381 role = store.sample_role(str(app)) 

382 payload = [pair_payload(app, store.get_pair(app, active, passive), role) for active, passive in pairs] 

383 return dict(pairs=payload, progress=progress(app), status=store.status(app)) 

384 

385 def write_response(unit_id:str, pairs:list[tuple[str, str]]) -> JSONResponse: 

386 return JSONResponse(write_payload(unit_id, pairs)) 

387 

388 async def save_suggestions(request:Request): 

389 data = await request.json() 

390 

391 def run(): 

392 try: 

393 unit_id = data.get("unit_id", "") 

394 pairs = parse_pairs(data) if data.get("pairs") else [] 

395 result = store.save_suggestions(unit_id, pairs, data.get("kind", "")) 

396 return JSONResponse(dict( 

397 write_payload(unit_id, result.written), 

398 written=result.written, 

399 skipped=[item.model_dump() for item in result.skipped], 

400 )) 

401 except AnnotationError as error: 

402 return error_response(error) 

403 

404 return await run_in_threadpool(run) 

405 

406 async def label(request:Request): 

407 return await run_in_threadpool(label_sync, await request.json()) 

408 

409 def label_sync(data:dict): 

410 try: 

411 unit_id = data.get("unit_id", "") 

412 pairs = parse_pairs(data) 

413 expected = parse_expected(data) 

414 category = data.get("category") 

415 if category is None: 

416 store.clear_classifications(unit_id, pairs, expected=expected) 

417 else: 

418 store.set_classifications( 

419 unit_id, pairs, category, 

420 justification=data.get("justification") or "", 

421 cert=data.get("cert") or "high", 

422 expected=expected, 

423 justification_source=data.get("justification_source") or None, 

424 ) 

425 return write_response(unit_id, pairs) 

426 except AnnotationError as error: 

427 return error_response(error) 

428 

429 def profile() -> dict: 

430 if not store.annotator: 

431 return dict(id=None, name=None, short_name=None, editable=False) 

432 name = store.annotator_full_name() 

433 saved = (load_display(display_path(store.path)).get("annotators") or {}).get(store.annotator) or {} 

434 return dict( 

435 id=store.annotator, 

436 name=name, 

437 short_name=saved.get("short_name") or initials(name) or store.annotator, 

438 editable=not store.read_only, 

439 ) 

440 

441 async def edit_profile(request:Request): 

442 data = await request.json() 

443 

444 def run(): 

445 try: 

446 if store.read_only: 

447 raise ReadOnlyError("This server is read-only.") 

448 if ("name" in data or "short_name" in data) and not store.annotator: 

449 raise AnnotationError("No annotator is set on this server (start it with --annotator, e.g. --annotator RT).") 

450 if (data.get("name") or "").strip() and data["name"].strip() != store.annotator_full_name(): 

451 store.set_annotator_name(data["name"]) 

452 path = display_path(store.path) 

453 display = load_display(path) 

454 if "title" in data: 

455 title = (data.get("title") or "").strip() 

456 if title: 

457 display["title"] = title 

458 else: 

459 display.pop("title", None) 

460 if "short_name" in data: 

461 annotators = display.setdefault("annotators", {}) 

462 short_name = (data.get("short_name") or "").strip() 

463 if short_name: 

464 annotators.setdefault(store.annotator, {})["short_name"] = short_name 

465 else: 

466 annotators.pop(store.annotator, None) 

467 if not annotators: 

468 display.pop("annotators") 

469 save_display(display, path) 

470 return JSONResponse(dict(profile=profile(), title=display.get("title"))) 

471 except AnnotationError as error: 

472 return error_response(error) 

473 return await run_in_threadpool(run) 

474 

475 async def viewing(request:Request): 

476 data = await request.json() 

477 

478 def run(): 

479 try: 

480 store.set_viewing(data.get("unit_id", "")) 

481 return JSONResponse(dict(unit_id=store.viewing().unit_id)) 

482 except AnnotationError as error: 

483 return error_response(error) 

484 return await run_in_threadpool(run) 

485 

486 async def certainty(request:Request): 

487 return await run_in_threadpool(certainty_sync, await request.json()) 

488 

489 def certainty_sync(data:dict): 

490 try: 

491 unit_id = data.get("unit_id", "") 

492 pairs = parse_pairs(data) 

493 store.set_certainty(unit_id, pairs, cert=data.get("cert") or "") 

494 return write_response(unit_id, pairs) 

495 except AnnotationError as error: 

496 return error_response(error) 

497 

498 def categories(request:Request): 

499 with store.lock: 

500 return JSONResponse(store.category_counts().model_dump()) 

501 

502 def category(request:Request): 

503 try: 

504 with store.lock: 

505 store.refresh() 

506 params = request.query_params 

507 pairs = views.category_pairs(store, request.path_params["name"], source=params.get("source") or "all") 

508 offset = max(int(params.get("offset") or 0), 0) 

509 limit = max(min(int(params.get("limit") or 100), 500), 1) 

510 roles = store.sample_roles() 

511 rows = [] 

512 for pair in pairs[offset:offset + limit]: 

513 app = pair.app 

514 role = roles.get(str(app)) 

515 rows.append(dict( 

516 pair_payload(app, pair, role), 

517 unit_id=str(app), 

518 sample_role=role, 

519 context=dict(before=app.text_before(), lemma=app.text(), after=app.text_after()), 

520 )) 

521 return JSONResponse(dict( 

522 category=store.get_relation_type(request.path_params["name"]).name, 

523 total=len(pairs), offset=offset, limit=limit, pairs=rows, 

524 version=current_version(), 

525 )) 

526 except AnnotationError as error: 

527 return error_response(error) 

528 except ValueError: 

529 return JSONResponse({"error": "offset and limit must be numbers."}, status_code=400) 

530 

531 def agreement(request:Request): 

532 try: 

533 with store.lock: 

534 store.refresh() 

535 params = request.query_params 

536 return JSONResponse(views.agreement( 

537 store, scope=params.get("scope") or None, source=params.get("source") or None, 

538 display_justification=display_justification, 

539 )) 

540 except AnnotationError as error: 

541 return error_response(error) 

542 

543 def definitions_write(method): 

544 async def endpoint(request:Request): 

545 data = await request.json() 

546 

547 def run(): 

548 try: 

549 return JSONResponse(method(data).model_dump()) 

550 except AnnotationError as error: 

551 return error_response(error) 

552 return await run_in_threadpool(run) 

553 return endpoint 

554 

555 update_category = definitions_write(lambda data: store.update_category( 

556 data.get("name", ""), description=data.get("description"), new_name=data.get("new_name") or None)) 

557 update_guidance = definitions_write(lambda data: store.update_guidance(data.get("guidance", ""))) 

558 update_classifier = definitions_write(lambda data: store.update_classifier_instructions(data.get("instructions", ""))) 

559 add_category = definitions_write(lambda data: store.add_category( 

560 data.get("name", ""), data.get("description", ""), 

561 inverse_name=data.get("inverse_name") or None, inverse_description=data.get("inverse_description") or "")) 

562 remove_category = definitions_write(lambda data: store.remove_category(data.get("name", ""), reassign_to=data.get("reassign_to") or None)) 

563 

564 routes = [ 

565 Route("/", index), 

566 Route("/api/config", config), 

567 Route("/api/queue", queue), 

568 Route("/api/sample-progress", sample_progress), 

569 Route("/api/version", version), 

570 Route("/api/unit/{unit_id:path}", unit), 

571 Route("/api/label", label, methods=["POST"]), 

572 Route("/api/certainty", certainty, methods=["POST"]), 

573 Route("/api/save-suggestions", save_suggestions, methods=["POST"]), 

574 Route("/api/viewing", viewing, methods=["POST"]), 

575 Route("/api/profile", edit_profile, methods=["POST"]), 

576 Route("/api/categories", categories), 

577 Route("/api/category/{name}", category), 

578 Route("/api/agreement", agreement), 

579 Route("/api/definitions/category", update_category, methods=["POST"]), 

580 Route("/api/definitions/guidance", update_guidance, methods=["POST"]), 

581 Route("/api/definitions/classifier", update_classifier, methods=["POST"]), 

582 Route("/api/definitions/add", add_category, methods=["POST"]), 

583 Route("/api/definitions/remove", remove_category, methods=["POST"]), 

584 Mount("/static", StaticFiles(directory=STATIC), name="static"), 

585 ] 

586 return Starlette(routes=routes, middleware=[Middleware(CacheControl)])