Coverage for rdgai/annotation.py: 97.45%
1570 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-24 23:53 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-24 23:53 +0000
1"""
2A service layer for querying and editing the classifications in a TEI file.
4This is used by the MCP server (``rdgai.mcp_server``) and is independent of MCP so that it can be tested
5and reused directly. The TEI file is the state: every write is saved to disk straight away.
6"""
7import os
8import re
9import json
10import hashlib
11import time
12import threading
13import tempfile
14from contextlib import contextmanager
15from pathlib import Path
16from datetime import datetime, timezone
17from typing import Literal
19from lxml import etree as ET
20from pydantic import BaseModel, Field
22from .apparatus import Doc, App, Pair, RelationType, tei_tag, unique, relation_provenance, prune_empty_list
23from .notes import resolve_references
24from .diff import describe_change, label_warning
25from . import search
26CLASSIFIER_GROUP_TYPE = "classifier"
27from .rules import SubreadingRule, Parents, Coverage, find_parents, coverage as rule_coverage, RULE_GROUP_TYPE, DEFAULT_SUFFIXES
29try:
30 import fcntl
31except ImportError: # pragma: no cover (Windows)
32 fcntl = None
33from .tei import find_element, find_elements, extract_text, find_parent, parse_tei
34from . import sampling
35from .sampling import Sample, default_sample_path
36from . import translations as translation_files
39DEFAULT_IGNORE_TYPES = ("defective",)
40CERTAINTY_VALUES = ("high", "medium", "low")
41RDGAI_RESP = "rdgai"
43DIRECTION_CONVENTION = (
44 "A category describes the change from the ACTIVE (first) reading to the PASSIVE (second) reading. "
45 "'Addition' means the passive reading has the extra words; 'Omission' means the passive reading lacks them. "
46 "Setting a category on a pair automatically sets the inverse category on the reverse pair."
47)
49UnitStatus = Literal["unclassified", "partial", "classified", "all"]
50SampleFilter = Literal["all", "sampled", "example", "test", "unsampled"]
53class AnnotationError(Exception):
54 pass
57class ReadOnlyError(AnnotationError):
58 pass
61class DefinitionsLockedError(AnnotationError):
62 pass
65class UnitNotFoundError(AnnotationError):
66 pass
69class ConflictError(AnnotationError):
70 """ A write was based on a stale view: the current categories differ from what the caller expected. """
71 def __init__(self, message:str, current:dict):
72 super().__init__(message)
73 self.current = current
76class _Unchecked:
77 def __repr__(self):
78 return "UNCHECKED"
81UNCHECKED = _Unchecked()
82SOURCE = re.compile(r"^(?P<name>[A-Za-z_][A-Za-z0-9_.\-]*)(?::(?P<model>\S+))?$")
85NC_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_.\-]*$")
86XML_ID = "{http://www.w3.org/XML/1998/namespace}id"
89# ---------------------------------------------------------------------------
90# Result models (these become the structured output of the MCP tools)
91# ---------------------------------------------------------------------------
93class Category(BaseModel):
94 name: str
95 description: str
96 inverse: str = Field(description="The category assigned to the reverse pair. Equal to name if the category is its own inverse.")
97 group: str = Field(default="", description="Optional grouping hint from the <interp>'s @type or @n (used to lay out GUI buttons).")
100class Definitions(BaseModel):
101 language: str
102 guidance: str = Field(description="Guidance given in the XML comment before the category definitions (e.g. a decision order).")
103 direction_convention: str
104 categories: list[Category]
105 definitions_hash: str = Field(description="SHA-256 of the guidance and the categories (name, description, inverse), and of the classifier instructions and constraints if any.")
106 classifier_instructions: str = Field(default="", description="This file's instructions for the classification pipeline (editable; empty if none).")
107 constraints: dict[str, list[str]] = Field(default_factory=dict, description="Constraints that categories declare on the computed change (category -> names), checked by the pipeline.")
110class DefinitionsChange(BaseModel):
111 message: str
112 relations_updated: int = Field(description="Number of labelled <relation> elements whose category was renamed or reassigned.")
113 changed: list[Category] = Field(default_factory=list, description="Categories added or changed, as they now are.")
114 removed: list[str] = Field(default_factory=list, description="Names of categories that no longer exist (removed or renamed).")
115 guidance: str | None = Field(default=None, description="The new guidance, if it was changed.")
116 definitions_hash: str = Field(description="The hash of the definitions after the change.")
119class Provenance(BaseModel):
120 resp: str = Field(default="", description="Who is responsible, e.g. '#RT' for a human annotator or '#rdgai' for the pipeline.")
121 cert: str = Field(default="", description="Certainty: high, medium or low.")
122 justification: str = ""
123 justification_source: str = Field(default="", description="If the justification's wording was copied from someone else (e.g. 'claude' from a suggestion), who.")
124 change: str = Field(default="", description="Pointers to <change> elements: the pipeline run (if any) and the definitions version.")
125 when: str = Field(default="", description="When the label was saved (ISO 8601, UTC), if recorded.")
126 model: str = Field(default="", description="The model used, if any.")
127 definitions_hash: str = Field(default="", description="Hash of the category definitions in force when the label was saved, if recorded.")
130class ChangeInfo(BaseModel):
131 kind: str = Field(description="identical, addition, omission, reordering or changed (from a word-level diff; a reading aid, not a category).")
132 text: str = Field(description="E.g. 'second reading adds: και'. A reading aid only, never a label.")
135class PairInfo(BaseModel):
136 active: str = Field(description="Identifier of the active (first) reading.")
137 passive: str = Field(description="Identifier of the passive (second) reading.")
138 active_text: str
139 passive_text: str
140 category: str | None = Field(description="Category for the change from active to passive, or null if unclassified.")
141 inverse_category: str | None = Field(description="Category on the reverse pair (passive to active).")
142 provenance: Provenance | None = None
143 source: Literal["human", "pipeline", "rule"] | None = Field(default=None, description="Who made the current label, if any.")
144 rule: int | None = Field(default=None, description="If a subreading rule covers this pair: 1 (subreading-parent), 2 (sibling subreadings) or 3 (copies the parents' pair). Such pairs are labelled automatically.")
145 change: ChangeInfo | None = Field(default=None, description="What changes from the active to the passive reading, from a word-level diff.")
146 warning: str | None = Field(default=None, description="Set if the category clearly contradicts the change (e.g. an Omission where the passive reading only adds words).")
149class NoteReferenceInfo(BaseModel):
150 label: str
151 unit_id: str | None = Field(description="The unit referred to, if it could be found.")
152 reading: str | None = None
155class NoteInfo(BaseModel):
156 text: str
157 references: list[NoteReferenceInfo] = Field(default_factory=list)
160class ReadingInfo(BaseModel):
161 id: str
162 text: str = Field(description="The reading text, or 'OMIT' for an empty reading (an omission). Notes are not included.")
163 notes: list[NoteInfo] = Field(default_factory=list, description="Editorial notes found in the reading text (not part of the reading).")
164 type: str = Field(default="", description="The reading's @type, e.g. orthographic or defective.")
165 witness_count: int
166 witnesses: list[str]
167 excluded: bool = Field(description="True if pairs with this reading are not classified (by default, defective readings).")
170class UnitSummary(BaseModel):
171 id: str
172 verse: str
173 lemma: str
174 reading_count: int
175 pair_count: int = Field(description="Number of unordered pairs of substantive readings to classify (excluding pairs covered by subreading rules).")
176 classified_count: int
177 status: str
178 sample_role: str | None = Field(default=None, description="'example' or 'test' if the unit is in the sample.")
179 rule_pair_count: int = Field(default=0, description="Pairs labelled automatically by subreading rules (not counted in pair_count).")
182class UnitDetail(BaseModel):
183 id: str
184 verse: str
185 context: str = Field(description="The verse with the variation unit marked ⸂…⸃ (⸆ marks an empty base text).")
186 context_before: str
187 context_after: str
188 readings: list[ReadingInfo]
189 lacunose_witnesses: list[str]
190 pairs: list[PairInfo] = Field(description="Each unordered pair of substantive readings, once.")
191 status: str
192 sample_role: str | None = Field(default=None, description="'example' or 'test' if the unit is in the sample.")
193 translations: dict[str, str] = Field(default_factory=dict, description="English translation of the whole verse with each reading in place, by reading id (if any have been made; see set_translations).")
196def check_translation_marks(reading_id:str, text:str):
197 """ The words that render the reading are marked ⸂…⸃ (possibly in several spans), never nested or unclosed. """
198 depth = 0
199 for character in text:
200 if character == "⸂":
201 depth += 1
202 elif character == "⸃":
203 depth -= 1
204 if depth not in (0, 1):
205 raise AnnotationError(
206 f"The marks in the translation for reading '{reading_id}' are unbalanced: mark the words that render "
207 "the reading as ⸂…⸃ (several spans are allowed, but not nested), and an omission with ⸆."
208 )
209 if depth:
210 raise AnnotationError(f"The translation for reading '{reading_id}' has a ⸂ without a closing ⸃.")
213class ViewingInfo(BaseModel):
214 unit_id: str = Field(description="The unit open in the annotation GUI.")
215 when: str = Field(description="When the GUI opened it (ISO 8601, UTC).")
218class TranslationResult(BaseModel):
219 unit_id: str
220 saved: list[str] = Field(description="Reading ids whose translations were saved.")
221 missing: list[str] = Field(description="Substantive readings of the unit that still have no translation.")
222 saved_to: str
225class UntranslatedList(BaseModel):
226 total: int = Field(description="Units matching the filters with a substantive reading not yet translated.")
227 unit_ids: list[str]
230class UnitList(BaseModel):
231 total: int = Field(description="Number of units matching the filters.")
232 offset: int
233 units: list[UnitSummary]
236class CategoryCount(BaseModel):
237 category: str
238 total: int = Field(description="Number of directed pairs (active → passive) with this category.")
239 human: int = Field(description="Of which classified by a human annotator.")
240 pipeline: int = Field(description="Of which classified by the rdgai pipeline (tentative).")
241 rule: int = Field(default=0, description="Of which labelled by a subreading rule.")
244class CategoryCounts(BaseModel):
245 pairs_to_classify: int = Field(description="Unordered pairs of substantive readings to classify (excluding pairs covered by subreading rules).")
246 classified: int = Field(description="Of which classified.")
247 rule_pairs: int = Field(default=0, description="Unordered pairs covered by subreading rules.")
248 categories: list[CategoryCount]
251class CategoryPair(BaseModel):
252 unit_id: str
253 context: str
254 pair: PairInfo
257class CategoryPairList(BaseModel):
258 category: str
259 total: int
260 offset: int
261 pairs: list[CategoryPair]
264class SampleProgress(BaseModel):
265 role: str
266 units: int
267 units_classified: int = Field(description="Units whose pairs are all classified.")
268 pairs: int = Field(description="Pairs to annotate (excluding pairs covered by subreading rules).")
269 pairs_classified: int
270 rule_pairs: int = Field(default=0, description="Pairs labelled automatically by subreading rules.")
273class SampleUnitStatus(BaseModel):
274 id: str
275 role: str
276 status: str
277 pair_count: int
278 classified_count: int
279 rule_pair_count: int = 0
282class SampleInfo(BaseModel):
283 exists: bool
284 path: str
285 seed: int | None = None
286 size: int | None = None
287 test_fraction: float | None = None
288 max_pairs: int | None = None
289 eligible_count: int | None = None
290 created: str | None = None
291 progress: list[SampleProgress] = Field(default_factory=list, description="Progress for all sampled units and by role.")
292 units: list[SampleUnitStatus] = Field(default_factory=list, description="The sampled units in document order.")
295class SuggestionInfo(BaseModel):
296 unit_id: str
297 active: str
298 passive: str
299 category: str
300 source: str = Field(description="Who made the suggestion, e.g. 'claude' or 'rdgai:<model>'.")
301 model: str = ""
302 justification: str = ""
303 cert: str = ""
304 when: str = ""
305 definitions_hash: str = ""
308class SuggestionResult(BaseModel):
309 unit_id: str
310 suggestion: SuggestionInfo
311 inverse: SuggestionInfo
314class SuggestionList(BaseModel):
315 suggestions: list[SuggestionInfo]
318class RuleConfig(BaseModel):
319 reading_type: str
320 category: str
321 suffix: str
324class RuleCount(BaseModel):
325 rule: int = Field(description="1: a subreading and its parent; 2: two subreadings of the same parent and type.")
326 covered: int = Field(description="Unordered pairs covered by this rule.")
327 written: int = Field(description="Pairs whose rule label was written or updated.")
328 unchanged: int = Field(description="Pairs whose rule label was already correct.")
329 human: int = Field(default=0, description="Pairs left alone because a human labelled them.")
332class RuleReading(BaseModel):
333 unit_id: str
334 reading: str
335 parent: str | None = None
338class RuleConflict(BaseModel):
339 unit_id: str
340 active: str
341 passive: str
342 label: str = Field(description="The human label (kept).")
343 rule_label: str = Field(description="What the rule would give.")
344 rule: int
347class RulesReport(BaseModel):
348 rules: list[RuleConfig]
349 counts: list[RuleCount]
350 removed: int = Field(default=0, description="Leftover rule labels removed from pairs no rule covers (e.g. written by the former rule 3). Human and pipeline labels are never removed.")
351 descriptions_updated: list[str] = Field(default_factory=list, description="Stored rules whose description in the TEI was out of date and is rewritten.")
352 unresolved: list[RuleReading] = Field(description="Typed readings whose parent could not be found (not guessed).")
353 nested: list[RuleReading] = Field(description="Subreadings of subreadings (skipped).")
354 conflicts: list[RuleConflict] = Field(description="Human labels that disagree with the rules (kept).")
355 dry_run: bool
358class SimilarPair(BaseModel):
359 corpus: str = Field(description="'target' for this file (other corpora are references).")
360 unit_id: str
361 verse: str = Field(description="E.g. 'Mark 2:27'.")
362 active: str
363 passive: str
364 active_text: str
365 passive_text: str
366 change: str
367 category: str
368 source: str = Field(description="human, or pipeline (tentative).")
369 tentative: bool = Field(description="True for pipeline labels: weigh them much less than human (certain) labels.")
370 cert: str = ""
371 justification: str = ""
372 definitions_hash: str = ""
373 score: float
376class SimilarResults(BaseModel):
377 query: dict
378 results: list[SimilarPair]
381class DecisionsResult(BaseModel):
382 written: list[tuple[str, str]] = Field(default_factory=list)
383 skipped: list[tuple[str, str]] = Field(default_factory=list, description="Pairs labelled by someone else meanwhile (left as they are).")
386class SkippedPair(BaseModel):
387 pair: tuple[str, str]
388 why: str
391class SavedSuggestions(BaseModel):
392 written: list[tuple[str, str]] = Field(default_factory=list)
393 skipped: list[SkippedPair] = Field(default_factory=list)
396# a reason saved on the inverse pair starts like this; copied into a label for the pair as shown, it says so instead
397INVERSE_REASON = re.compile(r"^Inverse of (\S+) → (\S+):\s*")
400def reason_for_pair(justification:str) -> str:
401 """ A suggestion's reason as it reads for the pair shown: one written for the other direction says so. """
402 match = INVERSE_REASON.match(justification or "")
403 if match:
404 return f"Written for {match[1]} → {match[2]}: {justification[match.end():]}"
405 return (justification or "").strip()
408class WriteResult(BaseModel):
409 unit_id: str
410 pair: PairInfo
411 inverse: PairInfo
412 saved_to: str
415# ---------------------------------------------------------------------------
416# The store
417# ---------------------------------------------------------------------------
419def verse_of(unit_id:str) -> str:
420 """ 'Mark.1.1.12-16' -> 'Mark.1.1'. Returns the id unchanged if it is not in that form. """
421 parts = unit_id.split(".")
422 if len(parts) >= 4:
423 return ".".join(parts[:3])
424 return unit_id
427def matches_verse(unit_id:str, verse:str) -> bool:
428 verse = verse.strip().rstrip(".")
429 return unit_id == verse or unit_id.startswith(verse + ".")
432class AnnotationStore:
433 """
434 Wraps a TEI file for reading and writing classifications of reading pairs.
436 Args:
437 path: The TEI file. It is modified in place on every write.
438 annotator: The xml:id of the human responsible for writes made through this store (e.g. 'RT').
439 annotator_name: Optional full name, used when adding a <respStmt> for the annotator.
440 read_only: If True, all writes raise ReadOnlyError.
441 lock_definitions: If True, the category definitions cannot be edited (classifications still can).
442 ignore_types: Readings with these @type values are excluded from pairs (teiphy collapses them).
443 sample_path: The sidecar YAML file holding the sample of units (default: <file>.sample.yaml).
444 translations_path: The sidecar YAML file holding contextual translations (default: <file>.translations.yaml).
445 check_sample: Check on loading that an existing sample was drawn with the same ignore_types.
446 reading_notes: Split notes in parentheses off reading texts (see rdgai.notes).
447 lock_timeout: Seconds to wait for another process's write lock on the file.
448 evaluation: Evaluation mode: no read reveals the labels or suggestions of the sample's test units, test units
449 cannot be changed, and the definitions are locked. Requires a sample.
450 """
451 def __init__(
452 self,
453 path:Path|str,
454 annotator:str|None=None,
455 annotator_name:str|None=None,
456 read_only:bool=False,
457 lock_definitions:bool=False,
458 ignore_types:tuple[str,...]|list[str]=DEFAULT_IGNORE_TYPES,
459 sample_path:Path|str|None=None,
460 translations_path:Path|str|None=None,
461 check_sample:bool=True,
462 reading_notes:bool=True,
463 lock_timeout:float=10.0,
464 evaluation:bool=False,
465 ):
466 self.path = Path(path)
467 if not self.path.exists():
468 raise FileNotFoundError(self.path)
469 self.sample_path = Path(sample_path) if sample_path else default_sample_path(self.path)
470 self.translations_path = Path(translations_path) if translations_path else translation_files.default_translations_path(self.path)
471 self.lock_path = self.path.with_name(f".{self.path.name}.lock")
472 self.viewing_path = self.path.with_name(f".{self.path.name}.viewing.json")
473 self._viewing = None
474 self.reading_notes = reading_notes
475 self.lock_timeout = lock_timeout
476 self._write_depth = 0
477 self.annotator = annotator.lstrip("#") if annotator else None
478 self.annotator_name = annotator_name
479 self.read_only = read_only
480 self.evaluation = evaluation
481 self.lock_definitions = lock_definitions or evaluation
482 self.ignore_types = set(ignore_types)
483 self.lock = threading.RLock()
484 self.doc: Doc
485 self._file_id = None
486 self.load()
487 if check_sample or evaluation:
488 self.load_sample() # fails early if the sample was drawn with different settings
489 if evaluation and self.load_sample() is None:
490 raise AnnotationError(
491 f"Evaluation mode needs a sample of example and test units ({self.sample_path.name} not found): draw one first."
492 )
494 # -- loading and saving --------------------------------------------------
496 def file_id(self) -> tuple:
497 """ Identifies the file's current version (a replaced file has a new inode even if its mtime is unchanged). """
498 stat = self.path.stat()
499 return (stat.st_ino, stat.st_mtime_ns, stat.st_size)
501 @staticmethod
502 def identity(stat:os.stat_result) -> tuple:
503 return (stat.st_ino, stat.st_mtime_ns, stat.st_size)
505 def load(self, data:bytes|None=None, stat:os.stat_result|None=None):
506 """
507 Loads the file. Its identity and its content come from one open file, so they always belong to the same
508 version: if another process replaces the file meanwhile, the store still knows which version it holds.
509 (Recording the identity after parsing could pair old content with a newer identity, and the next write would
510 then skip the reload and save over the other process's work.)
511 """
512 with self.lock:
513 if data is None:
514 with open(self.path, "rb") as handle:
515 stat = os.fstat(handle.fileno())
516 data = handle.read()
517 self.doc = Doc(self.path, tree=parse_tei(data), reading_notes=self.reading_notes)
518 self._file_id = self.identity(stat)
519 self._digest = hashlib.sha256(data).digest()
520 self.rules = self.read_rules()
521 self._file_pairs = None # the whole-file pair structure (file_progress) belongs to the old document
523 def sync_for_write(self):
524 """
525 Called with the write lock held: reloads unless the file's bytes are exactly what this store holds. Compares
526 the content itself, so a write can't be fooled by a file identity that looks unchanged (a reused inode).
527 """
528 with open(self.path, "rb") as handle:
529 stat = os.fstat(handle.fileno())
530 data = handle.read()
531 if hashlib.sha256(data).digest() != self._digest:
532 self.load(data, stat)
533 else:
534 self._file_id = self.identity(stat)
536 def refresh(self):
537 """ Reloads the file if it has been changed by another program (e.g. a second rdgai process). """
538 with self.lock:
539 if self.file_id() != self._file_id:
540 self.load()
542 @contextmanager
543 def writing(self):
544 """
545 Holds this store's lock and an advisory lock on the lock file next to the TEI file, so that only one
546 process writes at a time. Writers reload the file inside the lock, so no other process's work is lost.
547 """
548 with self.lock:
549 if self._write_depth > 0 or fcntl is None:
550 if self._write_depth == 0:
551 self.sync_for_write()
552 self._write_depth += 1
553 try:
554 yield
555 finally:
556 self._write_depth -= 1
557 return
558 handle = open(self.lock_path, "a")
559 try:
560 deadline = time.monotonic() + self.lock_timeout
561 while True:
562 try:
563 fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
564 break
565 except BlockingIOError:
566 if time.monotonic() >= deadline:
567 raise AnnotationError(
568 f"{self.path.name} is locked by another process that is writing to it. Try again shortly."
569 )
570 time.sleep(0.05)
571 # with the lock held, nobody else can change the file: make sure this store holds its current content
572 self.sync_for_write()
573 self._write_depth += 1
574 try:
575 yield
576 finally:
577 self._write_depth -= 1
578 fcntl.flock(handle, fcntl.LOCK_UN)
579 finally:
580 handle.close()
582 def save(self):
583 with self.lock:
584 # TEI requires at least one <relation> in a <listRelation>: remove emptied lists (also those left by older versions)
585 for list_type in ("transcriptional", "suggestion"):
586 for list_relation in unique(find_elements(self.doc.tree, f".//listRelation[@type='{list_type}']")):
587 prune_empty_list(list_relation)
588 fd, tmp = tempfile.mkstemp(dir=self.path.parent, prefix=f".{self.path.name}.", suffix=".tmp")
589 os.close(fd)
590 try:
591 self.doc.write(tmp)
592 with open(tmp, "rb") as handle:
593 digest = hashlib.sha256(handle.read()).digest()
594 os.replace(tmp, self.path)
595 finally:
596 if os.path.exists(tmp):
597 os.remove(tmp)
598 self._file_id = self.file_id()
599 self._digest = digest
601 def check_writable(self):
602 if self.read_only:
603 raise ReadOnlyError("This server is read-only: classifications cannot be changed.")
605 # -- lookups ---------------------------------------------------------------
607 def get_app(self, unit_id:str) -> App:
608 try:
609 return self.doc[unit_id]
610 except KeyError:
611 raise UnitNotFoundError(f"No variation unit with id '{unit_id}'.")
613 def is_excluded(self, reading) -> bool:
614 return reading.type in self.ignore_types
616 def substantive_pairs(self, app:App) -> list[Pair]:
617 return [
618 pair for pair in app.non_redundant_pairs
619 if not self.is_excluded(pair.active) and not self.is_excluded(pair.passive)
620 ]
622 def get_pair(self, app:App, active:str, passive:str) -> Pair:
623 for reading_id in (active, passive):
624 if reading_id not in app.id_to_reading:
625 raise AnnotationError(
626 f"Unit '{app}' has no reading '{reading_id}'. Readings: {', '.join(app.id_to_reading)}."
627 )
628 if active == passive:
629 raise AnnotationError("The active and passive readings must be different.")
630 for pair in app.pairs:
631 if pair.active.n == active and pair.passive.n == passive:
632 if self.is_excluded(pair.active) or self.is_excluded(pair.passive):
633 raise AnnotationError(
634 f"Pair {active}→{passive} in '{app}' involves a reading of type "
635 f"{', '.join(sorted(self.ignore_types))} and is not classified."
636 )
637 return pair
638 raise AnnotationError(f"No pair {active}→{passive} in unit '{app}'.") # pragma: no cover
640 def get_relation_type(self, name:str) -> RelationType:
641 name = name.lstrip("#")
642 if name not in self.doc.relation_types:
643 raise AnnotationError(
644 f"Unknown category '{name}'. Categories: {', '.join(self.doc.relation_types)}."
645 )
646 return self.doc.relation_types[name]
648 def hides(self, app:App) -> bool:
649 """ In evaluation mode, nothing about the labels or suggestions of test units is revealed. """
650 return self.evaluation and self.sample_role(str(app)) == "test"
652 def check_unit_writable(self, app:App):
653 """ In evaluation mode test units cannot be changed (refused the same way whether labelled or not). """
654 if self.hides(app):
655 raise AnnotationError(f"In evaluation mode, test unit {app} cannot be changed.")
657 def is_classified(self, pair:Pair) -> bool:
658 if self.hides(pair.app):
659 return False
660 return bool(pair.types) or bool(pair.get_inverse().types)
662 def status(self, app:App) -> str:
663 pairs = self.work_pairs(app)
664 if not pairs:
665 return "nothing_to_classify"
666 classified = sum(self.is_classified(pair) for pair in pairs)
667 if classified == 0:
668 return "unclassified"
669 if classified == len(pairs):
670 return "classified"
671 return "partial"
673 def file_progress(self) -> dict:
674 """
675 Labelled pairs and complete units in the whole file. Which pairs need a label depends only on the document
676 (not on the labels), so each pair and its inverse are worked out once per loaded document and reused; only the
677 labels are checked each time.
678 """
679 with self.lock:
680 if getattr(self, "_file_pairs", None) is None:
681 units = []
682 for app in self.doc.apps:
683 directed = {(pair.active.n, pair.passive.n): pair for pair in app.pairs}
684 units.append((app, [(pair, directed[(pair.passive.n, pair.active.n)]) for pair in self.work_pairs(app)]))
685 self._file_pairs = units
686 counts = dict(pairs_done=0, pairs_total=0, units_done=0, units_total=0)
687 for app, pairs in self._file_pairs:
688 hidden = self.hides(app)
689 done = 0 if hidden else sum(bool(pair.types) or bool(inverse.types) for pair, inverse in pairs)
690 counts["pairs_done"] += done
691 counts["pairs_total"] += len(pairs)
692 counts["units_done"] += done == len(pairs)
693 counts["units_total"] += 1
694 return counts
696 def changes_by_id(self) -> dict:
697 return {
698 element.attrib.get(XML_ID): element
699 for element in unique(find_elements(self.doc.tree, ".//revisionDesc/change"))
700 }
702 def change_info(self, change:str) -> dict:
703 """
704 Looks up the <change> elements referenced by a relation's @change attribute: a pipeline run or model
705 (giving the model and the run's time) and the definitions version (giving the definitions hash).
706 """
707 info = dict(run_when="", model="", definitions_hash="")
708 if not change:
709 return info
710 changes = self.changes_by_id()
711 for token in change.split():
712 element = changes.get(token.lstrip("#"))
713 if element is None:
714 continue
715 if element.attrib.get("type") == "definitions":
716 idno = next(iter(unique(find_elements(element, ".//idno"))), None)
717 info["definitions_hash"] = (idno.text or "").strip() if idno is not None else ""
718 continue
719 model = next((extract_text(name, include_tail=False) for name in unique(find_elements(element, ".//name[@type='model']"))), "")
720 if model:
721 info["model"] = model
722 if element.attrib.get("when") and element.attrib.get("type") != "model":
723 info["run_when"] = element.attrib["when"]
724 return info
726 def provenance_from_relation(self, relation) -> Provenance:
727 data = relation_provenance(relation)
728 info = self.change_info(data["change"])
729 return Provenance(
730 resp=data["resp"],
731 cert=data["cert"],
732 justification=data["justification"],
733 justification_source=data["justification_source"],
734 change=data["change"],
735 when=data["when"] or info["run_when"],
736 model=info["model"],
737 definitions_hash=info["definitions_hash"],
738 )
740 # -- serialisation -----------------------------------------------------------
742 def pair_info(self, pair:Pair) -> PairInfo:
743 category = sorted(pair.relation_type_names())
744 inverse_category = sorted(pair.get_inverse().relation_type_names())
745 provenance = None
746 relation = pair.relation_element()
747 hidden = self.hides(pair.app)
748 if hidden:
749 category, inverse_category, relation = [], [], None
750 if relation is not None:
751 provenance = self.provenance_from_relation(relation)
752 covered = self.coverage_for(pair)
753 change = describe_change(pair.active.text, pair.passive.text)
754 return PairInfo(
755 active=pair.active.n,
756 passive=pair.passive.n,
757 active_text=str(pair.active),
758 passive_text=str(pair.passive),
759 category=" ".join(category) or None,
760 inverse_category=" ".join(inverse_category) or None,
761 provenance=provenance,
762 source=None if hidden else self.label_source(pair),
763 rule=covered.rule if covered else None,
764 change=ChangeInfo(kind=change.kind, text=change.text),
765 warning=label_warning(" ".join(category) or None, change),
766 )
768 def unit_summary(self, app:App) -> UnitSummary:
769 pairs = self.work_pairs(app)
770 lemma = extract_text(find_element(app.element, ".//lem"))
771 return UnitSummary(
772 id=str(app),
773 verse=verse_of(str(app)),
774 lemma=lemma or "OMIT",
775 reading_count=len(app.readings),
776 pair_count=len(pairs),
777 classified_count=sum(self.is_classified(pair) for pair in pairs),
778 status=self.status(app),
779 sample_role=self.sample_role(str(app)),
780 rule_pair_count=len(self.rule_pairs(app)),
781 )
783 # -- read operations -----------------------------------------------------------
785 def categories(self) -> list[Category]:
786 return [
787 Category(
788 name=relation_type.name,
789 description=relation_type.description,
790 inverse=relation_type.get_inverse().name,
791 group=relation_type.element.attrib.get("type") or relation_type.element.attrib.get("n") or "",
792 )
793 for relation_type in self.doc.relation_types.values()
794 ]
796 def definitions_hash(self) -> str:
797 """
798 SHA-256 of the guidance and the categories (name, description, inverse) in the loaded document, and of the
799 classifier instructions and constraints when there are any (so files without them keep their hash).
800 """
801 content = dict(
802 guidance=self.doc.get_definitions_comment(),
803 categories=[[category.name, category.description, category.inverse] for category in self.categories()],
804 )
805 instructions, constraints = self.classifier_instructions(), self.category_constraints()
806 if instructions or constraints:
807 content["classifier"] = dict(instructions=instructions, constraints={name: constraints[name] for name in sorted(constraints)})
808 canonical = json.dumps(content, ensure_ascii=False)
809 return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
811 def definitions(self) -> Definitions:
812 with self.lock:
813 self.refresh()
814 return Definitions(
815 language=self.doc.language,
816 guidance=self.doc.get_definitions_comment(),
817 direction_convention=DIRECTION_CONVENTION,
818 categories=self.categories(),
819 definitions_hash=self.definitions_hash(),
820 classifier_instructions=self.classifier_instructions(),
821 constraints=self.category_constraints(),
822 )
824 def filter_units(self, status:UnitStatus="all", verse:str="", sample:SampleFilter="all") -> list[App]:
825 """ The units matching the filters, in document order (call refresh() first). """
826 apps = self.doc.apps
827 if sample != "all":
828 roles = self.sample_roles()
829 if sample == "sampled":
830 apps = [app for app in apps if str(app) in roles]
831 elif sample == "unsampled":
832 apps = [app for app in apps if str(app) not in roles]
833 else:
834 apps = [app for app in apps if roles.get(str(app)) == sample]
835 if verse:
836 apps = [app for app in apps if matches_verse(str(app), verse)]
837 if status != "all":
838 apps = [app for app in apps if self.status(app) == status]
839 return apps
841 def list_units(
842 self,
843 status:UnitStatus="all",
844 verse:str="",
845 sample:SampleFilter="all",
846 offset:int=0,
847 limit:int=50,
848 ) -> UnitList:
849 with self.lock:
850 self.refresh()
851 apps = self.filter_units(status=status, verse=verse, sample=sample)
852 offset = max(offset, 0)
853 limit = max(min(limit, 500), 1)
854 return UnitList(
855 total=len(apps),
856 offset=offset,
857 units=[self.unit_summary(app) for app in apps[offset:offset+limit]],
858 )
860 def note_info(self, app:App, note:str) -> NoteInfo:
861 references = resolve_references(note, str(app), self.doc.id_to_app.keys())
862 return NoteInfo(
863 text=note,
864 references=[NoteReferenceInfo(label=ref.label, unit_id=ref.unit_id, reading=ref.reading) for ref in references],
865 )
867 def ordered_pairs(self, app:App) -> list[Pair]:
868 """
869 The unordered pairs of substantive readings, each oriented with the better-attested reading first
870 (ties in document order), sorted by the attestation rank of their readings.
871 """
872 readings = [reading for reading in app.readings if not self.is_excluded(reading)]
873 ranked = sorted(readings, key=lambda reading: (-len(reading.witnesses), app.readings.index(reading)))
874 directed = {(pair.active.n, pair.passive.n): pair for pair in app.pairs}
875 return [
876 directed[(ranked[i].n, ranked[j].n)]
877 for i in range(len(ranked))
878 for j in range(i + 1, len(ranked))
879 ]
881 def reading_ordered_pairs(self, app:App) -> list[Pair]:
882 """
883 The unordered pairs of substantive readings in reading order, each with the earlier reading first:
884 a → b, a → c, …, b → c, … (the GUI's order; the pipeline and MCP use ``ordered_pairs``).
885 """
886 readings = [reading for reading in app.readings if not self.is_excluded(reading)]
887 directed = {(pair.active.n, pair.passive.n): pair for pair in app.pairs}
888 return [
889 directed[(readings[i].n, readings[j].n)]
890 for i in range(len(readings))
891 for j in range(i + 1, len(readings))
892 ]
894 def get_unit(self, unit_id:str, pair_order:Literal["document", "attestation"]="document") -> UnitDetail:
895 with self.lock:
896 self.refresh()
897 app = self.get_app(unit_id)
898 pairs = self.ordered_pairs(app) if pair_order == "attestation" else self.substantive_pairs(app)
899 readings = [
900 ReadingInfo(
901 id=reading.n,
902 text=str(reading),
903 notes=[self.note_info(app, note) for note in reading.notes],
904 type=reading.type,
905 witness_count=len(reading.witnesses),
906 witnesses=reading.witnesses,
907 excluded=self.is_excluded(reading),
908 )
909 for reading in app.readings
910 ]
911 return UnitDetail(
912 id=str(app),
913 verse=verse_of(str(app)),
914 context=app.text_in_context(),
915 context_before=app.text_before(),
916 context_after=app.text_after(),
917 readings=readings,
918 lacunose_witnesses=app.lacunae(),
919 pairs=[self.pair_info(pair) for pair in pairs],
920 status=self.status(app),
921 sample_role=self.sample_role(str(app)),
922 translations=self.translations_for(app),
923 )
925 def directed_pairs(self):
926 """ Yields every directed pair of substantive readings in the document. """
927 for app in self.doc.apps:
928 for pair in app.pairs:
929 if not self.is_excluded(pair.active) and not self.is_excluded(pair.passive):
930 yield pair
932 @staticmethod
933 def is_pipeline(pair:Pair) -> bool:
934 return pair.rdgai_responsible()
936 def category_counts(self) -> CategoryCounts:
937 with self.lock:
938 self.refresh()
939 counts = {name: CategoryCount(category=name, total=0, human=0, pipeline=0, rule=0) for name in self.doc.relation_types}
940 for pair in self.directed_pairs():
941 if self.hides(pair.app):
942 continue
943 source = self.label_source(pair)
944 for name in pair.relation_type_names():
945 count = counts.setdefault(name, CategoryCount(category=name, total=0, human=0, pipeline=0, rule=0))
946 count.total += 1
947 setattr(count, source, getattr(count, source) + 1)
948 pairs = [pair for app in self.doc.apps for pair in self.work_pairs(app)]
949 return CategoryCounts(
950 pairs_to_classify=len(pairs),
951 classified=sum(self.is_classified(pair) for pair in pairs),
952 rule_pairs=sum(len(self.rule_pairs(app)) for app in self.doc.apps),
953 categories=list(counts.values()),
954 )
956 def list_category(
957 self,
958 category:str,
959 source:Literal["all", "human", "pipeline"]="all",
960 offset:int=0,
961 limit:int=50,
962 ) -> CategoryPairList:
963 """ Lists the directed pairs with a category, in document order. """
964 with self.lock:
965 self.refresh()
966 relation_type = self.get_relation_type(category)
967 pairs = [pair for pair in self.directed_pairs() if relation_type in pair.types and not self.hides(pair.app)]
968 if source == "human":
969 pairs = [pair for pair in pairs if not self.is_pipeline(pair)]
970 elif source == "pipeline":
971 pairs = [pair for pair in pairs if self.is_pipeline(pair)]
972 offset = max(offset, 0)
973 limit = max(min(limit, 500), 1)
974 return CategoryPairList(
975 category=relation_type.name,
976 total=len(pairs),
977 offset=offset,
978 pairs=[
979 CategoryPair(unit_id=str(pair.app), context=pair.app.text_in_context(), pair=self.pair_info(pair))
980 for pair in pairs[offset:offset+limit]
981 ],
982 )
984 # -- editing the definitions ---------------------------------------------------------
986 def check_definitions_editable(self):
987 self.check_writable()
988 if self.lock_definitions:
989 raise DefinitionsLockedError("The category definitions are locked on this server.")
991 def check_new_category_name(self, name:str):
992 if not name or not NC_NAME.match(name):
993 raise AnnotationError(
994 f"'{name}' is not a valid category name: use letters, digits, '_', '-' or '.', starting with a letter or '_'."
995 )
996 if name in self.doc.relation_types:
997 raise AnnotationError(f"A category named '{name}' already exists.")
998 for element in self.doc.tree.getroot().iter():
999 if isinstance(element.tag, str) and element.attrib.get(XML_ID) == name:
1000 raise AnnotationError(f"'{name}' is already used as an xml:id in the document.")
1002 def category_relations(self, list_type:str="transcriptional") -> list:
1003 """ The <relation> elements in all <listRelation type="..."> lists (labels or suggestions). """
1004 relations = []
1005 for list_relation in unique(find_elements(self.doc.tree, f".//listRelation[@type='{list_type}']")):
1006 relations.extend(unique(find_elements(list_relation, ".//relation")))
1007 return relations
1009 def relations_using(self, names:set[str], list_type:str="transcriptional") -> list:
1010 pointers = {f"#{name}" for name in names}
1011 return [
1012 relation for relation in self.category_relations(list_type)
1013 if pointers & set(relation.attrib.get("ana", "").split())
1014 ]
1016 def rename_in_relations(self, mapping:dict[str, str]) -> int:
1017 """
1018 Replaces category pointers in @ana (old name -> new name) in labels and suggestions.
1019 Returns the number of labels changed.
1020 """
1021 pointers = {f"#{old}": f"#{new}" for old, new in mapping.items()}
1022 for rule_interp in self.rule_interps() + self.constraint_interps():
1023 if rule_interp.get("ana") in pointers:
1024 rule_interp.set("ana", pointers[rule_interp.get("ana")])
1025 labels_changed = 0
1026 for list_type in ("transcriptional", "suggestion"):
1027 for relation in self.relations_using(set(mapping), list_type):
1028 tokens = []
1029 for token in relation.attrib.get("ana", "").split():
1030 token = pointers.get(token, token)
1031 if token not in tokens:
1032 tokens.append(token)
1033 relation.set("ana", " ".join(tokens))
1034 if list_type == "transcriptional":
1035 labels_changed += 1
1036 return labels_changed
1038 @staticmethod
1039 def set_interp_text(interp, text:str):
1040 for child in list(interp):
1041 interp.remove(child)
1042 interp.text = text
1044 def commit_definitions(
1045 self,
1046 message:str,
1047 relations_updated:int=0,
1048 changed:list[str]|None=None,
1049 removed:list[str]|None=None,
1050 guidance:str|None=None,
1051 ) -> DefinitionsChange:
1052 """
1053 Saves the file and reloads it so that categories and pairs are rebuilt from the TEI.
1054 Returns only what changed and the new hash (not the full definitions).
1055 """
1056 self.save()
1057 self.load()
1058 categories = {category.name: category for category in self.categories()}
1059 return DefinitionsChange(
1060 message=message,
1061 relations_updated=relations_updated,
1062 changed=[categories[name] for name in (changed or []) if name in categories],
1063 removed=list(removed or []),
1064 guidance=guidance,
1065 definitions_hash=self.definitions_hash(),
1066 )
1068 def update_category(self, name:str, description:str|None=None, new_name:str|None=None) -> DefinitionsChange:
1069 """
1070 Changes the description and/or the name of a category.
1071 Renaming also updates the inverse's @corresp and every classification and suggestion that uses the category.
1072 """
1073 with self.writing():
1074 self.check_definitions_editable()
1075 self.refresh()
1076 relation_type = self.get_relation_type(name)
1077 name = relation_type.name
1078 inverse_name = relation_type.get_inverse().name
1079 renaming = new_name is not None and new_name != name
1080 if description is None and not renaming:
1081 raise AnnotationError("Nothing to change: give a new description or a new name.")
1083 relations_updated = 0
1084 if renaming:
1085 self.check_new_category_name(new_name)
1086 interp = relation_type.element
1087 if description is not None:
1088 self.set_interp_text(interp, description.strip())
1089 if renaming:
1090 interp.set(XML_ID, new_name)
1091 for other in self.doc.relation_types.values():
1092 if other.element.attrib.get("corresp", "") == f"#{name}":
1093 other.element.set("corresp", f"#{new_name}")
1094 relations_updated = self.rename_in_relations({name: new_name})
1096 message = f"Renamed '{name}' to '{new_name}'." if renaming else f"Updated the description of '{name}'."
1097 if renaming and description is not None:
1098 message = f"Renamed '{name}' to '{new_name}' and updated its description."
1099 changed = [new_name if renaming else name]
1100 if renaming and inverse_name != name:
1101 changed.append(inverse_name)
1102 return self.commit_definitions(
1103 message, relations_updated, changed=changed, removed=[name] if renaming else [],
1104 )
1106 def add_category(
1107 self,
1108 name:str,
1109 description:str,
1110 inverse_name:str|None=None,
1111 inverse_description:str="",
1112 ) -> DefinitionsChange:
1113 """
1114 Adds a category. Without inverse_name it is its own inverse; with inverse_name a reciprocal pair
1115 of categories is added, linked with @corresp.
1116 """
1117 with self.writing():
1118 self.check_definitions_editable()
1119 self.refresh()
1120 self.check_new_category_name(name)
1121 if inverse_name is not None:
1122 if inverse_name == name:
1123 raise AnnotationError("The inverse category's name must be different from the category's name.")
1124 self.check_new_category_name(inverse_name)
1125 description = (description or "").strip()
1126 inverse_description = (inverse_description or "").strip()
1127 if not description:
1128 raise AnnotationError("A description is required for the new category.")
1129 if inverse_name is not None and not inverse_description:
1130 raise AnnotationError("A description is required for the inverse category.")
1132 interp_group = self.doc.get_interpgrp()
1133 tag = tei_tag(interp_group, "interp")
1134 attrib = {XML_ID: name}
1135 if inverse_name:
1136 attrib["corresp"] = f"#{inverse_name}"
1137 ET.SubElement(interp_group, tag, attrib=attrib).text = description
1138 if inverse_name:
1139 ET.SubElement(interp_group, tag, attrib={XML_ID: inverse_name, "corresp": f"#{name}"}).text = inverse_description
1140 return self.commit_definitions(f"Added '{name}' and its inverse '{inverse_name}'.", changed=[name, inverse_name])
1141 return self.commit_definitions(f"Added '{name}' (its own inverse).", changed=[name])
1143 def remove_category(self, name:str, reassign_to:str|None=None) -> DefinitionsChange:
1144 """
1145 Removes a category together with its inverse. If any pairs are labelled with them, reassign_to must name a
1146 category with a corresponding inverse (the labels and suggestions are moved to it, keeping their provenance).
1147 Without reassign_to, suggestions that use the removed categories are deleted.
1148 """
1149 with self.writing():
1150 self.check_definitions_editable()
1151 self.refresh()
1152 relation_type = self.get_relation_type(name)
1153 inverse = relation_type.get_inverse()
1154 removed = {relation_type.name, inverse.name}
1155 removed_text = f"'{relation_type.name}'" + (f" and its inverse '{inverse.name}'" if inverse is not relation_type else "")
1156 rules_using = [rule.resp_id for rule in self.rules if rule.category in removed]
1157 if rules_using and reassign_to is None:
1158 raise AnnotationError(
1159 f"Cannot remove {removed_text}: used by subreading rule {', '.join(rules_using)}. "
1160 "Pass reassign_to to move the rule and its labels to another category."
1161 )
1163 relations_updated = 0
1164 dropped_suggestions = 0
1165 if reassign_to is not None:
1166 target = self.get_relation_type(reassign_to)
1167 if target.name in removed:
1168 raise AnnotationError(f"Cannot reassign to '{target.name}': it is being removed.")
1169 target_inverse = target.get_inverse()
1170 if (inverse is relation_type) != (target_inverse is target):
1171 raise AnnotationError(
1172 f"Cannot reassign {removed_text} to '{target.name}' (inverse '{target_inverse.name}'): "
1173 "a category that is its own inverse can only be reassigned to another such category, "
1174 "and a reciprocal pair only to another reciprocal pair."
1175 )
1176 relations_updated = self.rename_in_relations({relation_type.name: target.name, inverse.name: target_inverse.name})
1177 else:
1178 in_use = len(self.relations_using(removed))
1179 if in_use:
1180 raise AnnotationError(
1181 f"Cannot remove {removed_text}: used by {in_use} pairs. "
1182 "Pass reassign_to to move these classifications to another category."
1183 )
1184 suggestions = self.relations_using(removed, "suggestion")
1185 dropped_suggestions = len({
1186 (find_parent(relation, "app").get(XML_ID), frozenset((relation.get("active"), relation.get("passive"))), relation.get("resp"), relation.get("change"))
1187 for relation in suggestions
1188 })
1189 for relation in suggestions:
1190 relation.getparent().remove(relation)
1192 for removed_name in removed:
1193 element = self.doc.relation_types[removed_name].element
1194 element.getparent().remove(element)
1195 if reassign_to is None:
1196 for interp in self.constraint_interps():
1197 if interp.get("ana", "").lstrip("#") in removed:
1198 interp.getparent().remove(interp)
1199 self.prune_classifier_group()
1201 message = f"Removed {removed_text}."
1202 if reassign_to is not None:
1203 message += f" Reassigned {relations_updated} pairs to '{target.name}'."
1204 if dropped_suggestions:
1205 message += f" Deleted {dropped_suggestions} suggestion{'s' if dropped_suggestions != 1 else ''} that used it."
1206 return self.commit_definitions(message, relations_updated, removed=sorted(removed))
1208 def update_guidance(self, guidance:str) -> DefinitionsChange:
1209 """ Replaces the guidance comment (e.g. the decision order) placed before the category definitions. """
1210 with self.writing():
1211 self.check_definitions_editable()
1212 self.refresh()
1213 guidance = (guidance or "").strip()
1214 if "--" in guidance or guidance.endswith("-"):
1215 raise AnnotationError("The guidance cannot contain '--' or end with '-' (it is stored in an XML comment).")
1216 interp_group = self.doc.get_interpgrp()
1217 for sibling in list(interp_group.itersiblings(preceding=True)):
1218 if not isinstance(sibling, ET._Comment):
1219 break
1220 sibling.getparent().remove(sibling)
1221 if guidance:
1222 interp_group.addprevious(ET.Comment(f"\n{guidance}\n"))
1223 return self.commit_definitions("Updated the guidance.", guidance=guidance)
1225 # -- similarity search ---------------------------------------------------------------
1227 TENTATIVE_WEIGHT = 0.5
1229 def search_index(self):
1230 """
1231 The labelled directed pairs (human and pipeline, never rules) with their search terms and a BM25 index,
1232 rebuilt when the file changes. Test units are left out in evaluation mode.
1233 """
1234 if getattr(self, "_search_cache", (None,))[0] == self._file_id:
1235 return self._search_cache[1]
1236 entries = []
1237 for app in self.doc.apps:
1238 if self.hides(app):
1239 continue
1240 before, after = app.text_before(), app.text_after()
1241 for pair in app.pairs:
1242 if self.is_excluded(pair.active) or self.is_excluded(pair.passive):
1243 continue
1244 source = self.label_source(pair)
1245 if source not in ("human", "pipeline"):
1246 continue
1247 terms = search.pair_terms(pair.active.text, pair.passive.text, before, after)
1248 entries.append((app, pair, source, terms))
1249 index = search.BM25([terms for _, _, _, terms in entries])
1250 self._search_cache = (self._file_id, (entries, index))
1251 return entries, index
1253 def search_similar(
1254 self,
1255 unit_id:str,
1256 active:str,
1257 passive:str,
1258 limit:int=10,
1259 sources:tuple[str, ...]|list[str]=("human", "pipeline"),
1260 categories:list[str]|tuple[str, ...]|set[str]|None=None,
1261 ) -> list[SimilarPair]:
1262 """
1263 Labelled pairs whose change resembles the change from active to passive in this unit, best first, optionally
1264 only those labelled with one of `categories`.
1265 Pipeline (tentative) labels count for less than human ones. The pair itself and its inverse are never
1266 returned, so a label cannot be evidence for itself.
1267 """
1268 with self.lock:
1269 self.refresh()
1270 app = self.get_app(unit_id)
1271 pair = self.get_pair(app, active, passive)
1272 query = search.pair_terms(pair.active.text, pair.passive.text, app.text_before(), app.text_after())
1273 entries, index = self.search_index()
1274 scored = []
1275 for (candidate_app, candidate, source, _), score in zip(entries, index.scores(query)):
1276 if score <= 0 or source not in sources:
1277 continue
1278 if candidate_app is app and {candidate.active.n, candidate.passive.n} == {active, passive}:
1279 continue
1280 if categories is not None and self.current_category(candidate) not in categories:
1281 continue
1282 weighted = score * (self.TENTATIVE_WEIGHT if source == "pipeline" else 1.0)
1283 scored.append((weighted, candidate_app, candidate, source))
1284 scored.sort(key=lambda item: -item[0])
1285 results = []
1286 for score, candidate_app, candidate, source in scored[:max(limit, 0)]:
1287 provenance = self.provenance_from_relation(candidate.relation_element())
1288 results.append(SimilarPair(
1289 corpus="target",
1290 unit_id=str(candidate_app),
1291 verse=search.verse_label(str(candidate_app)),
1292 active=candidate.active.n,
1293 passive=candidate.passive.n,
1294 active_text=str(candidate.active),
1295 passive_text=str(candidate.passive),
1296 change=describe_change(candidate.active.text, candidate.passive.text).text,
1297 category=self.current_category(candidate) or "",
1298 source=source,
1299 tentative=source == "pipeline",
1300 cert=provenance.cert,
1301 justification=provenance.justification,
1302 definitions_hash=provenance.definitions_hash,
1303 score=round(score, 3),
1304 ))
1305 return results
1307 # -- classifier instructions and category constraints --------------------------------
1308 #
1309 # Stored next to the category definitions:
1310 # <interpGrp type="classifier">
1311 # <interp type="instructions">…text for the pipeline…</interp>
1312 # <interp type="constraint" ana="#SomeCategory">adds-only</interp>
1313 # </interpGrp>
1315 def classifier_group(self, create:bool=False):
1316 text = find_element(self.doc.tree, ".//text")
1317 group = find_element(text, f".//interpGrp[@type='{CLASSIFIER_GROUP_TYPE}']") if text is not None else None
1318 if group is None and create:
1319 categories = self.doc.get_interpgrp()
1320 group = ET.Element(tei_tag(categories, "interpGrp"), attrib={"type": CLASSIFIER_GROUP_TYPE})
1321 anchor = self.rule_group() if self.rule_group() is not None else categories
1322 anchor.addnext(group)
1323 return group
1325 def prune_classifier_group(self):
1326 group = self.classifier_group()
1327 if group is not None and not len(group):
1328 group.getparent().remove(group)
1330 def constraint_interps(self) -> list:
1331 group = self.classifier_group()
1332 return [interp for interp in find_elements(group, "./interp") if interp.get("type") == "constraint"] if group is not None else []
1334 def classifier_instructions(self) -> str:
1335 """ This file's instructions for the classification pipeline ('' if none). """
1336 group = self.classifier_group()
1337 if group is None:
1338 return ""
1339 interp = next((interp for interp in find_elements(group, "./interp") if interp.get("type") == "instructions"), None)
1340 return extract_text(interp).strip() if interp is not None else ""
1342 def category_constraints(self) -> dict[str, list[str]]:
1343 """ The constraints categories declare on the computed change: {category: [constraint names]}. """
1344 result = {}
1345 for interp in self.constraint_interps():
1346 name = interp.get("ana", "").lstrip("#")
1347 names = (extract_text(interp) or "").split()
1348 if name and names:
1349 result.setdefault(name, []).extend(names)
1350 return result
1352 def update_classifier_instructions(self, instructions:str) -> DefinitionsChange:
1353 """ Replaces this file's classifier instructions (an empty text removes them). """
1354 with self.writing():
1355 self.check_definitions_editable()
1356 self.refresh()
1357 instructions = (instructions or "").strip()
1358 group = self.classifier_group(create=bool(instructions))
1359 if group is not None:
1360 for interp in [interp for interp in find_elements(group, "./interp") if interp.get("type") == "instructions"]:
1361 group.remove(interp)
1362 if instructions:
1363 interp = ET.Element(tei_tag(group, "interp"), attrib={"type": "instructions"})
1364 interp.text = instructions
1365 group.insert(0, interp)
1366 self.prune_classifier_group()
1367 return self.commit_definitions("Updated the classifier instructions.")
1369 def set_category_constraints(self, category:str, constraints:list[str]) -> DefinitionsChange:
1370 """ Sets the constraints a category declares on the computed change (an empty list removes them). """
1371 from .constraints import CONSTRAINTS
1372 with self.writing():
1373 self.check_definitions_editable()
1374 self.refresh()
1375 name = self.get_relation_type(category).name
1376 unknown = [constraint for constraint in constraints if constraint not in CONSTRAINTS]
1377 if unknown:
1378 raise AnnotationError(f"Unknown constraint {', '.join(unknown)}: use {', '.join(CONSTRAINTS)}.")
1379 for interp in self.constraint_interps():
1380 if interp.get("ana", "").lstrip("#") == name:
1381 interp.getparent().remove(interp)
1382 if constraints:
1383 group = self.classifier_group(create=True)
1384 interp = ET.SubElement(group, tei_tag(group, "interp"), attrib={"type": "constraint", "ana": f"#{name}"})
1385 interp.text = " ".join(dict.fromkeys(constraints))
1386 self.prune_classifier_group()
1387 return self.commit_definitions(f"Set the constraints of '{name}' to {', '.join(constraints) or 'none'}.", changed=[name])
1389 # -- subreading rules ----------------------------------------------------------------
1391 def rule_interps(self) -> list:
1392 group = self.rule_group()
1393 return unique(find_elements(group, "./interp")) if group is not None else []
1395 def rule_group(self, create:bool=False):
1396 text = find_element(self.doc.tree, ".//text")
1397 group = find_element(text, f".//interpGrp[@type='{RULE_GROUP_TYPE}']") if text is not None else None
1398 if group is None and create:
1399 categories = self.doc.get_interpgrp()
1400 group = ET.Element(tei_tag(categories, "interpGrp"), attrib={"type": RULE_GROUP_TYPE})
1401 categories.addnext(group)
1402 return group
1404 def read_rules(self) -> list[SubreadingRule]:
1405 """ The subreading rules stored in the TEI file. """
1406 rules = []
1407 for interp in self.rule_interps():
1408 reading_type = interp.get("type", "")
1409 category = interp.get("ana", "").lstrip("#")
1410 suffix = interp.get("n") or DEFAULT_SUFFIXES.get(reading_type, "")
1411 if reading_type and category and suffix:
1412 rules.append(SubreadingRule(reading_type=reading_type, category=category, suffix=suffix))
1413 return rules
1415 def write_rules(self, rules:list[SubreadingRule]):
1416 """ Stores the rules in <interpGrp type="subreading-rules"> next to the category definitions. """
1417 group = self.rule_group(create=True)
1418 for child in list(group):
1419 group.remove(child)
1420 for rule in rules:
1421 interp = ET.SubElement(group, tei_tag(group, "interp"), attrib={
1422 XML_ID: rule.resp_id, "type": rule.reading_type, "ana": f"#{rule.category}", "n": rule.suffix,
1423 })
1424 interp.text = rule.description()
1426 def check_rules(self, rules:list[SubreadingRule]):
1427 types = [rule.reading_type for rule in rules]
1428 if len(set(types)) != len(types):
1429 raise AnnotationError("Each reading type can have only one rule.")
1430 for rule in rules:
1431 self.get_relation_type(rule.category)
1432 if not rule.reading_type or not rule.suffix or not re.match(r"^[A-Za-z0-9_.\-]+$", rule.suffix):
1433 raise AnnotationError(f"Invalid rule for '{rule.reading_type}': give a reading type and an id suffix (e.g. 'o').")
1435 def rule_parents(self, app:App, rules:list[SubreadingRule]|None=None) -> Parents:
1436 return find_parents(app, self.rules if rules is None else rules)
1438 def coverage_for(self, pair:Pair, parents:Parents|None=None) -> Coverage|None:
1439 if not self.rules and parents is None:
1440 return None
1441 if self.is_excluded(pair.active) or self.is_excluded(pair.passive):
1442 return None
1443 parents = parents or self.rule_parents(pair.app)
1444 return rule_coverage(pair.active.n, pair.passive.n, parents)
1446 def rule_pairs(self, app:App) -> list[Pair]:
1447 """ Unordered substantive pairs covered by a subreading rule (labelled automatically). """
1448 if not self.rules:
1449 return []
1450 parents = self.rule_parents(app)
1451 return [pair for pair in self.substantive_pairs(app) if rule_coverage(pair.active.n, pair.passive.n, parents)]
1453 def work_pairs(self, app:App) -> list[Pair]:
1454 """ Unordered substantive pairs for an annotator (not covered by a subreading rule). """
1455 if not self.rules:
1456 return self.substantive_pairs(app)
1457 parents = self.rule_parents(app)
1458 return [pair for pair in self.substantive_pairs(app) if not rule_coverage(pair.active.n, pair.passive.n, parents)]
1460 @staticmethod
1461 def label_source(pair:Pair) -> str|None:
1462 relation = pair.relation_element()
1463 if relation is None:
1464 return None
1465 resp = relation.get("resp", "")
1466 if resp.startswith("#rule-"):
1467 return "rule"
1468 if resp == f"#{RDGAI_RESP}":
1469 return "pipeline"
1470 return "human"
1472 def is_tentative(self, pair:Pair) -> bool:
1473 """ Pipeline labels are tentative (rule labels never are: they depend only on the reading types). """
1474 return self.label_source(pair) == "pipeline"
1476 @staticmethod
1477 def run_tokens(relation) -> list[str]:
1478 return [token for token in relation.get("change", "").split() if not token.startswith("#defs-")]
1480 def restore_rule_labels(self, app:App, pairs:list[Pair]):
1481 """
1482 After labels are cleared: pairs covered by a rule get the rule's label back (so clearing a human override of
1483 a rule label restores it). Rule labels depend only on the reading types, so no other write re-applies them.
1484 """
1485 if self.rules:
1486 self.apply_rules_to_app(app, self.rules, report=None, only={frozenset((pair.active.n, pair.passive.n)) for pair in pairs})
1488 def apply_rules_to_app(self, app:App, rules:list[SubreadingRule], report:dict|None, only:set|None=None) -> bool:
1489 """
1490 Applies the rules to one unit (or to the given unordered pairs of it). Rule labels left on pairs no rule
1491 covers (written by the former rule 3) are removed. Returns True if anything changed.
1492 """
1493 parents = self.rule_parents(app, rules)
1494 by_type = {rule.reading_type: rule for rule in rules}
1495 changed = False
1496 definitions_change = None
1497 when = self.now()
1498 if report is not None:
1499 report["unresolved"].extend(RuleReading(unit_id=str(app), reading=reading) for reading in parents.unresolved)
1500 report["nested"].extend(RuleReading(unit_id=str(app), reading=reading, parent=parent) for reading, parent in parents.nested)
1502 for pair in self.substantive_pairs(app):
1503 if only is not None and frozenset((pair.active.n, pair.passive.n)) not in only:
1504 continue
1505 covered = rule_coverage(pair.active.n, pair.passive.n, parents)
1506 if covered is None:
1507 # a leftover rule label (e.g. from the former rule 3): remove it; human and pipeline labels stay
1508 leftover = [directed for directed in (pair, pair.get_inverse()) if self.label_source(directed) == "rule"]
1509 for directed in leftover:
1510 directed.clear_types()
1511 if leftover:
1512 changed = True
1513 if report is not None:
1514 report["removed"] += 1
1515 continue
1516 counts = report["counts"][covered.rule] if report is not None else {}
1517 if report is not None:
1518 counts["covered"] += 1
1519 rule = by_type[covered.reading_type]
1520 first, second = pair.active.n, pair.passive.n
1522 relation_type = self.get_relation_type(rule.category)
1523 if covered.rule == 1 and parents.parents.get(first) == second:
1524 relation_type = relation_type.get_inverse() # subreading -> parent
1525 if covered.rule == 1:
1526 subreading = second if parents.parents.get(second) == first else first
1527 article = "an" if covered.reading_type[:1].lower() in "aeiou" else "a"
1528 justification = f"{subreading} is {article} {covered.reading_type} subreading of {parents.parents[subreading]}."
1529 else:
1530 justification = f"{first} and {second} are both {covered.reading_type} subreadings of {parents.parents[first]}."
1532 source = self.label_source(pair)
1533 if source == "human":
1534 if report is not None:
1535 counts["human"] += 1
1536 current = self.current_category(pair)
1537 if current != relation_type.name:
1538 report["conflicts"].append(RuleConflict(
1539 unit_id=str(app), active=first, passive=second, label=current or "",
1540 rule_label=relation_type.name, rule=covered.rule,
1541 ))
1542 continue
1544 relation = pair.relation_element()
1545 inverse_relation = pair.get_inverse().relation_element()
1546 resp = f"#{rule.resp_id}"
1547 if (
1548 source == "rule" and relation is not None and inverse_relation is not None
1549 and self.current_category(pair) == relation_type.name
1550 and self.current_category(pair.get_inverse()) == relation_type.get_inverse().name
1551 and relation.get("resp") == resp and relation.get("cert") == "high"
1552 and relation_provenance(relation)["justification"] == justification
1553 and not self.run_tokens(relation)
1554 ):
1555 if report is not None:
1556 counts["unchanged"] += 1
1557 continue
1559 if definitions_change is None:
1560 definitions_change = self.ensure_definitions_change()
1561 pair.set_type_with_inverse(
1562 relation_type,
1563 responsible=resp,
1564 cert="high",
1565 description=justification,
1566 inverse_description=justification,
1567 change=self.change_pointers(definitions_change),
1568 when=when,
1569 )
1570 changed = True
1571 if report is not None:
1572 counts["written"] += 1
1573 return changed
1575 def update_rule_descriptions(self, rules:list[SubreadingRule]) -> list[str]:
1576 """ Rewrites the description of stored rules whose text is out of date (e.g. still describing rule 3). """
1577 by_id = {rule.resp_id: rule for rule in rules}
1578 updated = []
1579 for interp in self.rule_interps():
1580 rule = by_id.get(interp.get(XML_ID))
1581 if rule is not None and extract_text(interp).strip() != rule.description():
1582 self.set_interp_text(interp, rule.description())
1583 updated.append(rule.resp_id)
1584 return updated
1586 def apply_rules(self, rules:list[SubreadingRule]|None=None, dry_run:bool=False) -> RulesReport:
1587 """
1588 Labels the pairs formed by typed subreadings (see rdgai.rules). Rules given here are stored in the file
1589 (replacing the stored rules) unless dry_run; otherwise the stored rules are used. Human labels are never
1590 changed; those that disagree with a rule are reported as conflicts. Running again changes nothing.
1591 """
1592 with self.writing():
1593 if self.evaluation:
1594 raise AnnotationError("Subreading rules cannot be applied in evaluation mode (they would change test units).")
1595 if not dry_run:
1596 self.check_writable()
1597 self.refresh()
1598 rules = list(rules) if rules is not None else list(self.rules)
1599 if not rules:
1600 raise AnnotationError("No subreading rules configured: give rules, e.g. orthographic=Orthography.")
1601 self.check_rules(rules)
1602 report = dict(
1603 counts={number: dict(covered=0, written=0, unchanged=0, human=0) for number in (1, 2)},
1604 removed=0, unresolved=[], nested=[], conflicts=[],
1605 )
1606 changed = False
1607 descriptions_updated = []
1608 if rules != self.rules:
1609 self.write_rules(rules)
1610 changed = True
1611 else:
1612 descriptions_updated = self.update_rule_descriptions(rules)
1613 changed = bool(descriptions_updated)
1614 for app in self.doc.apps:
1615 changed = self.apply_rules_to_app(app, rules, report) or changed
1617 result = RulesReport(
1618 rules=[RuleConfig(reading_type=rule.reading_type, category=rule.category, suffix=rule.suffix) for rule in rules],
1619 counts=[RuleCount(rule=number, **values) for number, values in report["counts"].items()],
1620 removed=report["removed"],
1621 descriptions_updated=descriptions_updated,
1622 unresolved=report["unresolved"],
1623 nested=report["nested"],
1624 conflicts=report["conflicts"],
1625 dry_run=dry_run,
1626 )
1627 if dry_run:
1628 self.load() # discard the changes
1629 elif changed:
1630 self.save()
1631 self.load()
1632 return result
1634 # -- the unit open in the GUI (so that Claude can act on "the verse I'm on") ------------
1636 def set_viewing(self, unit_id:str):
1637 """
1638 Records the unit the GUI shows, in a small hidden file next to the TEI (so another process, e.g. a second
1639 MCP server, sees it). A read-only store keeps it in memory and writes nothing.
1640 """
1641 with self.lock:
1642 self.refresh()
1643 info = ViewingInfo(unit_id=str(self.get_app(unit_id)), when=sampling.now())
1644 self._viewing = info
1645 if self.read_only:
1646 return
1647 fd, tmp = tempfile.mkstemp(dir=self.viewing_path.parent, prefix=f"{self.viewing_path.name}.", suffix=".tmp")
1648 try:
1649 with os.fdopen(fd, "w", encoding="utf-8") as f:
1650 f.write(info.model_dump_json())
1651 os.replace(tmp, self.viewing_path)
1652 finally:
1653 if os.path.exists(tmp):
1654 os.remove(tmp)
1656 def viewing(self) -> ViewingInfo|None:
1657 """ The unit most recently opened in the GUI (by any process), if any. """
1658 try:
1659 from_file = ViewingInfo.model_validate_json(self.viewing_path.read_text(encoding="utf-8"))
1660 except (FileNotFoundError, ValueError):
1661 from_file = None
1662 candidates = [info for info in (from_file, self._viewing) if info is not None]
1663 return max(candidates, key=lambda info: info.when) if candidates else None
1665 # -- contextual translations (sidecar file) ------------------------------------------
1667 def load_translations(self) -> translation_files.Translations:
1668 """ Loads the translations from the sidecar file (cached until the file changes). """
1669 try:
1670 stat = self.translations_path.stat()
1671 key = (stat.st_ino, stat.st_mtime_ns, stat.st_size)
1672 except FileNotFoundError:
1673 return translation_files.Translations()
1674 if getattr(self, "_translations_cache", (None, None))[0] != key:
1675 self._translations_cache = (key, translation_files.load_translations(self.translations_path))
1676 return self._translations_cache[1]
1678 def translations_for(self, app:App) -> dict[str, str]:
1679 """ {reading id: translation} for a unit, leaving out translations made for a reading text that has changed. """
1680 entry = self.load_translations().units.get(str(app))
1681 if entry is None:
1682 return {}
1683 texts = {reading.n: str(reading) for reading in app.readings}
1684 return {
1685 reading_id: item.translation for reading_id, item in entry.readings.items()
1686 if texts.get(reading_id) == item.reading
1687 }
1689 def untranslated(self, app:App) -> list[str]:
1690 """ Substantive readings of a unit with no (current) translation. """
1691 done = self.translations_for(app)
1692 return [reading.n for reading in app.readings if not self.is_excluded(reading) and reading.n not in done]
1694 def untranslated_units(self, sample:SampleFilter="all", verse:str="") -> list[str]:
1695 with self.lock:
1696 self.refresh()
1697 return [
1698 str(app) for app in self.filter_units(sample=sample, verse=verse)
1699 if self.work_pairs(app) and self.untranslated(app)
1700 ]
1702 def set_translations(self, unit_id:str, translations:dict[str, str], source:str="claude") -> TranslationResult:
1703 """
1704 Saves translations of the verse with each reading in place (merged with the unit's existing ones).
1705 Only the sidecar file is written; the TEI is never changed.
1706 """
1707 with self.writing():
1708 self.check_writable()
1709 self.refresh()
1710 app = self.get_app(unit_id)
1711 if not translations:
1712 raise AnnotationError("Give at least one translation, as {reading id: translation}.")
1713 readings = {reading.n: reading for reading in app.readings}
1714 for reading_id, text in translations.items():
1715 if reading_id not in readings:
1716 raise AnnotationError(f"Unit '{unit_id}' has no reading '{reading_id}'. Readings: {', '.join(readings)}.")
1717 if not (text or "").strip():
1718 raise AnnotationError(f"The translation for reading '{reading_id}' is empty.")
1719 check_translation_marks(reading_id, text)
1720 data = translation_files.load_translations(self.translations_path)
1721 entry = data.units.setdefault(str(app), translation_files.UnitTranslations())
1722 for reading_id, text in translations.items():
1723 entry.readings[reading_id] = translation_files.ReadingTranslation(reading=str(readings[reading_id]), translation=text.strip())
1724 entry.source = source
1725 entry.when = sampling.now()
1726 translation_files.save_translations(data, self.translations_path)
1727 return TranslationResult(
1728 unit_id=str(app), saved=list(translations), missing=self.untranslated(app), saved_to=str(self.translations_path),
1729 )
1731 # -- sampling -----------------------------------------------------------------------
1733 def load_sample(self) -> Sample|None:
1734 """ Loads the sample from the sidecar file (cached until the file changes). """
1735 try:
1736 mtime = self.sample_path.stat().st_mtime_ns
1737 except FileNotFoundError:
1738 return None
1739 if getattr(self, "_sample_cache", (None, None))[0] != mtime:
1740 sample = sampling.load_sample(self.sample_path)
1741 if sorted(sample.ignore_types) != sorted(self.ignore_types):
1742 raise AnnotationError(
1743 f"The sample in {self.sample_path.name} was drawn ignoring reading types "
1744 f"{sorted(sample.ignore_types)}, but this server ignores {sorted(self.ignore_types)}. "
1745 "Use the same --ignore-type options, or draw a new sample."
1746 )
1747 self._sample_cache = (mtime, sample)
1748 return self._sample_cache[1]
1750 def sample_roles(self) -> dict[str, str]:
1751 sample = self.load_sample()
1752 return {unit.id: unit.role for unit in sample.units} if sample else {}
1754 def sample_role(self, unit_id:str) -> str|None:
1755 return self.sample_roles().get(unit_id)
1757 def eligible_units(self, max_pairs:int|None=None) -> list[App]:
1758 """ Units with at least one pair to classify (and at most max_pairs pairs, if given). """
1759 eligible = []
1760 for app in self.doc.apps:
1761 pair_count = len(self.substantive_pairs(app))
1762 if pair_count == 0:
1763 continue
1764 if max_pairs is not None and pair_count > max_pairs:
1765 continue
1766 eligible.append(app)
1767 return eligible
1769 def sample_info(self) -> SampleInfo:
1770 with self.lock:
1771 self.refresh()
1772 sample = self.load_sample()
1773 if sample is None:
1774 return SampleInfo(exists=False, path=str(self.sample_path))
1776 units = []
1777 for unit in sample.units:
1778 if unit.id not in self.doc.id_to_app:
1779 raise AnnotationError(f"Sampled unit '{unit.id}' is not in {self.path.name}.")
1780 app = self.doc[unit.id]
1781 pairs = self.work_pairs(app)
1782 units.append(SampleUnitStatus(
1783 id=unit.id,
1784 role=unit.role,
1785 status=self.status(app),
1786 pair_count=len(pairs),
1787 classified_count=sum(self.is_classified(pair) for pair in pairs),
1788 rule_pair_count=len(self.rule_pairs(app)),
1789 ))
1791 progress = []
1792 for role in ("all", "example", "test"):
1793 members = [unit for unit in units if role == "all" or unit.role == role]
1794 progress.append(SampleProgress(
1795 role=role,
1796 units=len(members),
1797 units_classified=sum(unit.status == "classified" for unit in members),
1798 pairs=sum(unit.pair_count for unit in members),
1799 pairs_classified=sum(unit.classified_count for unit in members),
1800 rule_pairs=sum(unit.rule_pair_count for unit in members),
1801 ))
1803 return SampleInfo(
1804 exists=True,
1805 path=str(self.sample_path),
1806 seed=sample.seed,
1807 size=sample.size,
1808 test_fraction=sample.test_fraction,
1809 max_pairs=sample.max_pairs,
1810 eligible_count=sample.eligible_count,
1811 created=sample.created,
1812 progress=progress,
1813 units=units,
1814 )
1816 def draw_sample(
1817 self,
1818 size:int,
1819 seed:int,
1820 test_fraction:float=0.5,
1821 max_pairs:int|None=None,
1822 overwrite:bool=False,
1823 ) -> SampleInfo:
1824 """
1825 Draws a reproducible random sample of units and splits it into example and test units.
1826 The sample is saved to the sidecar file. An existing sample is only replaced if overwrite is True.
1827 """
1828 with self.writing():
1829 if self.evaluation:
1830 raise AnnotationError("The sample cannot be drawn again in evaluation mode (it defines the test units).")
1831 self.check_writable()
1832 self.refresh()
1833 if self.sample_path.exists() and not overwrite:
1834 raise AnnotationError(
1835 f"A sample already exists in {self.sample_path.name}. Pass overwrite=True to replace it."
1836 )
1837 eligible = self.eligible_units(max_pairs=max_pairs)
1838 try:
1839 units = sampling.draw(
1840 [str(app) for app in eligible],
1841 size=size,
1842 seed=seed,
1843 test_fraction=test_fraction,
1844 document_order=[str(app) for app in self.doc.apps],
1845 )
1846 except ValueError as error:
1847 raise AnnotationError(str(error))
1849 sample = Sample(
1850 seed=seed,
1851 size=size,
1852 test_fraction=test_fraction,
1853 max_pairs=max_pairs,
1854 ignore_types=sorted(self.ignore_types),
1855 eligible_count=len(eligible),
1856 created=sampling.now(),
1857 source=self.path.name,
1858 units=units,
1859 )
1860 sampling.save_sample(sample, self.sample_path)
1861 return self.sample_info()
1863 # -- write operations -----------------------------------------------------------
1865 def resp_stmt_for(self, xml_id:str):
1866 for resp_stmt in unique(find_elements(self.doc.tree, ".//respStmt")):
1867 if resp_stmt.attrib.get(XML_ID) == xml_id:
1868 return resp_stmt
1869 return None
1871 def annotator_full_name(self) -> str|None:
1872 """ The annotator's name as recorded in the TEI (<respStmt xml:id="..."><name>), else as given when starting. """
1873 if not self.annotator:
1874 return None
1875 with self.lock:
1876 self.refresh()
1877 resp_stmt = self.resp_stmt_for(self.annotator)
1878 if resp_stmt is not None:
1879 for element in resp_stmt:
1880 if isinstance(element.tag, str) and ET.QName(element).localname in ("name", "persName"):
1881 text = extract_text(element).strip()
1882 if text:
1883 return text
1884 return self.annotator_name
1886 def set_annotator_name(self, name:str):
1887 """ Records the annotator's full name in the TEI header (<respStmt xml:id="..."><name>), and saves. """
1888 name = (name or "").strip()
1889 if not self.annotator:
1890 raise AnnotationError("No annotator is set on this server (start it with --annotator, e.g. --annotator RT).")
1891 if not name:
1892 raise AnnotationError("The name cannot be empty.")
1893 with self.writing():
1894 self.check_writable()
1895 self.refresh()
1896 resp_stmt = self.resp_stmt_for(self.annotator)
1897 if resp_stmt is None:
1898 self.ensure_resp_stmt(self.annotator, name, "classification of transcriptional changes")
1899 else:
1900 name_element = next((element for element in resp_stmt
1901 if isinstance(element.tag, str) and ET.QName(element).localname in ("name", "persName")), None)
1902 if name_element is None:
1903 name_element = ET.SubElement(resp_stmt, tei_tag(resp_stmt, "name"))
1904 for child in list(name_element):
1905 name_element.remove(child)
1906 name_element.text = name
1907 self.annotator_name = name
1908 self.save()
1910 def ensure_resp_stmt(self, xml_id:str, name:str, resp:str):
1911 """ Adds <respStmt xml:id="..."> to the titleStmt so that @resp pointers resolve. """
1912 tree = self.doc.tree
1913 for resp_stmt in unique(find_elements(tree, ".//respStmt")):
1914 if resp_stmt.attrib.get(XML_ID) == xml_id:
1915 return
1916 title_stmt = find_element(tree, ".//teiHeader/fileDesc/titleStmt")
1917 if title_stmt is None:
1918 return
1919 resp_stmt = ET.SubElement(title_stmt, tei_tag(title_stmt, "respStmt"), attrib={XML_ID: xml_id})
1920 ET.SubElement(resp_stmt, tei_tag(title_stmt, "resp")).text = resp
1921 ET.SubElement(resp_stmt, tei_tag(title_stmt, "name")).text = name
1923 def revision_desc(self):
1924 header = find_element(self.doc.tree, ".//teiHeader")
1925 revision_desc = find_element(header, ".//revisionDesc")
1926 if revision_desc is None:
1927 revision_desc = ET.SubElement(header, tei_tag(header, "revisionDesc"))
1928 return revision_desc
1930 @staticmethod
1931 def now() -> str:
1932 return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
1934 def ensure_definitions_change(self) -> str:
1935 """
1936 Returns the xml:id of the <change type="definitions"> recording the current definitions version,
1937 adding it to the revisionDesc if it is not there yet.
1938 """
1939 definitions_hash = self.definitions_hash()
1940 change_id = f"defs-{definitions_hash[:12]}"
1941 if change_id not in self.changes_by_id():
1942 revision_desc = self.revision_desc()
1943 change = ET.SubElement(
1944 revision_desc, tei_tag(revision_desc, "change"),
1945 attrib={XML_ID: change_id, "type": "definitions", "when": self.now()},
1946 )
1947 change.text = "Category definitions version "
1948 idno = ET.SubElement(change, tei_tag(revision_desc, "idno"), attrib={"type": "sha256"})
1949 idno.text = definitions_hash
1950 idno.tail = "."
1951 return change_id
1953 def ensure_model_change(self, model:str) -> str:
1954 """ Returns the xml:id of a <change type="model"> naming a model, adding it if necessary. """
1955 slug = re.sub(r"[^A-Za-z0-9_.\-]", "-", model)
1956 change_id = f"model-{slug}"
1957 if change_id not in self.changes_by_id():
1958 revision_desc = self.revision_desc()
1959 change = ET.SubElement(revision_desc, tei_tag(revision_desc, "change"), attrib={XML_ID: change_id, "type": "model"})
1960 change.text = "Suggestions made with "
1961 name = ET.SubElement(change, tei_tag(revision_desc, "name"), attrib={"type": "model"})
1962 name.text = model
1963 name.tail = "."
1964 return change_id
1966 @staticmethod
1967 def change_pointers(*change_ids:str|None) -> str:
1968 return " ".join(f"#{change_id.lstrip('#')}" for change_id in change_ids if change_id)
1970 def resolve_resp(self, resp:str|None) -> str:
1971 resp = (resp or self.annotator or "").lstrip("#")
1972 if not resp:
1973 raise AnnotationError("No annotator is set: start the server with --annotator.")
1974 if resp == RDGAI_RESP:
1975 self.ensure_resp_stmt(RDGAI_RESP, "rdgai", "automatic classification")
1976 elif resp == self.annotator:
1977 self.ensure_resp_stmt(resp, self.annotator_name or resp, "classification of transcriptional changes")
1978 return resp
1980 @staticmethod
1981 def check_cert(cert:str|None, optional:bool=False):
1982 if optional and cert is None:
1983 return
1984 if cert not in CERTAINTY_VALUES:
1985 raise AnnotationError(f"cert must be one of {', '.join(CERTAINTY_VALUES)}.")
1987 def current_category(self, pair:Pair) -> str|None:
1988 return " ".join(sorted(pair.relation_type_names())) or None
1990 def check_expected(self, pairs:list[Pair], expected:dict):
1991 """ Raises ConflictError if any pair's current category differs from what the caller expected. """
1992 current = {}
1993 for pair in pairs:
1994 key = (pair.active.n, pair.passive.n)
1995 if key not in expected or expected[key] is UNCHECKED:
1996 continue
1997 want = expected[key].lstrip("#") if expected[key] else None
1998 have = self.current_category(pair)
1999 if want != have:
2000 current[key] = have
2001 if current:
2002 details = ", ".join(f"{active}→{passive} is now {category or 'unclassified'}" for (active, passive), category in current.items())
2003 raise ConflictError(f"The classification changed since it was read: {details}. Reload and try again.", current)
2005 def write_results(self, app:App, pairs:list[Pair]) -> list[WriteResult]:
2006 return [
2007 WriteResult(unit_id=str(app), pair=self.pair_info(pair), inverse=self.pair_info(pair.get_inverse()), saved_to=str(self.path))
2008 for pair in pairs
2009 ]
2011 def set_classifications(
2012 self,
2013 unit_id:str,
2014 pairs:list[tuple[str, str]],
2015 category:str,
2016 justification:str="",
2017 cert:str="high",
2018 resp:str|None=None,
2019 change:str|None=None,
2020 expected:dict|None=None,
2021 justification_source:str|None=None,
2022 ) -> list[WriteResult]:
2023 """
2024 Sets the same category on several pairs of a unit (each from its active to its passive reading),
2025 replacing existing categories and setting the inverses. All pairs are checked before anything is
2026 written, and the file is saved once.
2028 expected: optional {(active, passive): category or None}. If any pair's current category differs,
2029 ConflictError is raised and nothing is written.
2030 justification_source: if the justification's wording was copied from someone else (e.g. 'claude' from a
2031 suggestion), who; recorded as the @resp of the justification's <desc>.
2032 """
2033 with self.writing():
2034 self.check_writable()
2035 self.refresh()
2036 if not pairs:
2037 raise AnnotationError("No pairs given.")
2038 self.check_cert(cert)
2039 app = self.get_app(unit_id)
2040 self.check_unit_writable(app)
2041 pair_objects = [self.get_pair(app, active, passive) for active, passive in pairs]
2042 relation_type = self.get_relation_type(category)
2043 self.check_expected(pair_objects, expected or {})
2044 resp = self.resolve_resp(resp)
2045 description_resp = None
2046 if justification_source and (justification or "").strip():
2047 source_name = justification_source.lstrip("#")
2048 if not NC_NAME.match(source_name):
2049 raise AnnotationError(f"Invalid justification source '{justification_source}': use a name such as 'claude'.")
2050 if source_name == "claude":
2051 self.ensure_resp_stmt("claude", "Claude", "suggested classifications")
2052 description_resp = f"#{source_name}"
2054 change_attr = self.change_pointers(change, self.ensure_definitions_change())
2055 when = self.now()
2056 justification = (justification or "").strip()
2057 for pair in pair_objects:
2058 inverse_justification = f"Inverse of {pair.active.n} → {pair.passive.n}: {justification}" if justification else ""
2059 pair.set_type_with_inverse(
2060 relation_type,
2061 responsible=f"#{resp}",
2062 cert=cert,
2063 description=justification,
2064 inverse_description=inverse_justification,
2065 change=change_attr,
2066 when=when,
2067 description_resp=description_resp,
2068 )
2069 self.save()
2070 return self.write_results(app, pair_objects)
2072 def set_classification(
2073 self,
2074 unit_id:str,
2075 active:str,
2076 passive:str,
2077 category:str,
2078 justification:str="",
2079 cert:str="high",
2080 resp:str|None=None,
2081 change:str|None=None,
2082 expected_category=UNCHECKED,
2083 ) -> WriteResult:
2084 """
2085 Sets the category for the change from the active reading to the passive reading.
2086 Replaces any existing category, sets the inverse on the reverse pair and saves the file.
2087 The label records when it was saved and the definitions version in force.
2089 resp defaults to the store's annotator. If expected_category is given (a category, or None for
2090 'unclassified') and the pair's current category differs, ConflictError is raised.
2091 """
2092 return self.set_classifications(
2093 unit_id, [(active, passive)], category, justification=justification, cert=cert, resp=resp, change=change,
2094 expected={(active, passive): expected_category},
2095 )[0]
2097 def write_decisions(
2098 self,
2099 unit_id:str,
2100 decisions:list[tuple[str, str, str, str, str]],
2101 resp:str|None=None,
2102 change:str|None=None,
2103 ) -> DecisionsResult:
2104 """
2105 Writes several different decisions for one unit, (active, passive, category, justification, cert) each, with
2106 one save. Everything is checked before anything is written. Only unlabelled pairs are written: a pair that
2107 someone labelled meanwhile is skipped and reported, never overwritten. Used by the pipeline.
2108 """
2109 with self.writing():
2110 self.check_writable()
2111 self.refresh()
2112 app = self.get_app(unit_id)
2113 self.check_unit_writable(app)
2114 checked = []
2115 for active, passive, category, justification, cert in decisions:
2116 self.check_cert(cert)
2117 checked.append((self.get_pair(app, active, passive), self.get_relation_type(category), (justification or "").strip(), cert))
2118 resp = self.resolve_resp(resp)
2119 change_attr = self.change_pointers(change, self.ensure_definitions_change())
2120 when = self.now()
2121 result = DecisionsResult()
2122 for pair, relation_type, justification, cert in checked:
2123 key = (pair.active.n, pair.passive.n)
2124 if pair.relation_element() is not None or pair.get_inverse().relation_element() is not None:
2125 result.skipped.append(key)
2126 continue
2127 pair.set_type_with_inverse(
2128 relation_type,
2129 responsible=f"#{resp}",
2130 cert=cert,
2131 description=justification,
2132 inverse_description=f"Inverse of {key[0]} → {key[1]}: {justification}" if justification else "",
2133 change=change_attr,
2134 when=when,
2135 )
2136 result.written.append(key)
2137 if result.written:
2138 self.save()
2139 return result
2141 def save_suggestions(self, unit_id:str, pairs:list[tuple[str, str]], kind:Literal["labels", "reasons"]) -> SavedSuggestions:
2142 """
2143 The GUI's "Save all suggestions" (kind 'labels') and "Save all reasons" (kind 'reasons') for the given pairs of a
2144 unit, each in the direction shown, with one save. The annotator becomes responsible for what is saved; a copied
2145 reason is recorded as the suggester's wording.
2147 labels: an unlabelled pair whose suggestions all agree is labelled with that category, the suggestion's reason
2148 and its certainty (high if none). Labelled pairs, disagreeing suggestions and rule pairs are skipped.
2149 reasons: a pair the annotator labelled without a reason gets the reason of a suggestion for the same category.
2150 Existing reasons are never replaced. Nothing is saved on test units, whose suggestions the GUI hides.
2151 """
2152 if kind not in ("labels", "reasons"):
2153 raise AnnotationError("kind must be 'labels' or 'reasons'.")
2154 with self.writing():
2155 self.check_writable()
2156 self.refresh()
2157 app = self.get_app(unit_id)
2158 self.check_unit_writable(app)
2159 result = SavedSuggestions()
2160 if self.sample_role(str(app)) == "test" or self.hides(app):
2161 return result
2162 resp = self.resolve_resp(None)
2163 change_attr = self.change_pointers(None, self.ensure_definitions_change())
2164 when = self.now()
2165 for active, passive in pairs:
2166 pair = self.get_pair(app, active, passive)
2167 info = self.pair_info(pair)
2168 suggestions = self.suggestions_for(app, pair)
2169 skip = lambda why: result.skipped.append(SkippedPair(pair=(active, passive), why=why))
2170 if self.coverage_for(pair) is not None or info.source == "rule":
2171 skip("by rule")
2172 continue
2173 if kind == "labels":
2174 if info.category or info.inverse_category:
2175 skip("labelled")
2176 continue
2177 if not suggestions:
2178 skip("no suggestion")
2179 continue
2180 if len({suggestion.category for suggestion in suggestions}) > 1:
2181 skip("suggestions disagree")
2182 continue
2183 chosen = next((suggestion for suggestion in suggestions if suggestion.justification), suggestions[0])
2184 category, cert = chosen.category, chosen.cert or "high"
2185 else:
2186 if not info.category:
2187 skip("not labelled")
2188 continue
2189 if info.source != "human":
2190 skip(f"labelled by the {info.source}")
2191 continue
2192 if info.provenance is not None and info.provenance.justification:
2193 skip("has a reason")
2194 continue
2195 with_reasons = [suggestion for suggestion in suggestions if suggestion.justification]
2196 chosen = next((suggestion for suggestion in with_reasons if suggestion.category == info.category), None)
2197 if chosen is None:
2198 skip("different category" if with_reasons else "no suggested reason")
2199 continue
2200 category, cert = info.category, (info.provenance.cert if info.provenance else "") or "high"
2201 reason = reason_for_pair(chosen.justification)
2202 source_name = chosen.source.split(":")[0]
2203 description_resp = None
2204 if reason and NC_NAME.match(source_name):
2205 if source_name == "claude":
2206 self.ensure_resp_stmt("claude", "Claude", "suggested classifications")
2207 description_resp = f"#{source_name}"
2208 pair.set_type_with_inverse(
2209 self.get_relation_type(category),
2210 responsible=f"#{resp}",
2211 cert=cert,
2212 description=reason,
2213 inverse_description=f"Inverse of {active} → {passive}: {reason}" if reason else "",
2214 change=change_attr,
2215 when=when,
2216 description_resp=description_resp,
2217 )
2218 result.written.append((active, passive))
2219 if result.written:
2220 self.save()
2221 return result
2223 def set_certainty(self, unit_id:str, pairs:list[tuple[str, str]], cert:str) -> list[WriteResult]:
2224 """
2225 Changes the certainty of labelled pairs (and their inverses) without changing their categories or
2226 justifications. The annotator becomes responsible, and the time and definitions version are updated.
2227 """
2228 with self.writing():
2229 self.check_writable()
2230 self.refresh()
2231 if not pairs:
2232 raise AnnotationError("No pairs given.")
2233 self.check_cert(cert)
2234 app = self.get_app(unit_id)
2235 self.check_unit_writable(app)
2236 pair_objects = [self.get_pair(app, active, passive) for active, passive in pairs]
2237 unlabelled = [f"{pair.active.n}→{pair.passive.n}" for pair in pair_objects if pair.relation_element() is None]
2238 if unlabelled:
2239 raise AnnotationError(f"Pairs not classified, so their certainty cannot be set: {', '.join(unlabelled)}.")
2240 resp = self.resolve_resp(None)
2241 definitions_change = self.ensure_definitions_change()
2242 when = self.now()
2243 for pair in pair_objects:
2244 for directed in (pair, pair.get_inverse()):
2245 relation = directed.relation_element()
2246 if relation is None:
2247 continue
2248 relation.set("resp", f"#{resp}")
2249 relation.set("cert", cert)
2250 tokens = [token for token in relation.attrib.get("change", "").split() if not token.startswith("#defs-")]
2251 relation.set("change", self.change_pointers(*tokens, definitions_change))
2252 self.stamp(relation, when)
2253 self.save()
2254 return self.write_results(app, pair_objects)
2256 @staticmethod
2257 def stamp(relation, when:str):
2258 """ Sets the <date when> inside the relation's justification <desc>, creating them if necessary. """
2259 desc = next((child for child in relation if isinstance(child.tag, str) and ET.QName(child).localname == "desc"), None)
2260 if desc is None:
2261 desc = ET.SubElement(relation, tei_tag(relation, "desc"), attrib={"type": "justification"})
2262 date = next((child for child in desc if isinstance(child.tag, str) and ET.QName(child).localname == "date"), None)
2263 if date is None:
2264 date = ET.SubElement(desc, tei_tag(relation, "date"))
2265 date.set("when", when)
2267 def clear_classification(self, unit_id:str, active:str, passive:str, expected_category=UNCHECKED) -> WriteResult:
2268 """ Removes the classification of a pair and its inverse and saves the file. """
2269 with self.writing():
2270 self.check_writable()
2271 self.refresh()
2272 app = self.get_app(unit_id)
2273 self.check_unit_writable(app)
2274 pair = self.get_pair(app, active, passive)
2275 self.check_expected([pair], {(active, passive): expected_category})
2276 pair.clear_types_with_inverse()
2277 self.restore_rule_labels(app, [pair])
2278 self.save()
2279 return self.write_results(app, [pair])[0]
2281 def clear_classifications(self, unit_id:str, pairs:list[tuple[str, str]], expected:dict|None=None) -> list[WriteResult]:
2282 """ Removes the classifications of several pairs (and their inverses), saving once. All-or-nothing. """
2283 with self.writing():
2284 self.check_writable()
2285 self.refresh()
2286 if not pairs:
2287 raise AnnotationError("No pairs given.")
2288 app = self.get_app(unit_id)
2289 self.check_unit_writable(app)
2290 pair_objects = [self.get_pair(app, active, passive) for active, passive in pairs]
2291 self.check_expected(pair_objects, expected or {})
2292 for pair in pair_objects:
2293 pair.clear_types_with_inverse()
2294 self.restore_rule_labels(app, pair_objects)
2295 self.save()
2296 return self.write_results(app, pair_objects)
2298 def start_run(self, model:str, description:str="") -> str:
2299 """
2300 Records a pipeline run as a <change> in the revisionDesc and returns its xml:id.
2301 Relations written during the run point to it with @change.
2302 """
2303 with self.writing():
2304 self.check_writable()
2305 self.refresh()
2306 revision_desc = self.revision_desc()
2307 now = datetime.now(timezone.utc).replace(microsecond=0)
2308 change_id = f"rdgai-run-{now.strftime('%Y%m%dT%H%M%SZ')}"
2309 existing = set(self.changes_by_id())
2310 suffix = 1
2311 base = change_id
2312 while change_id in existing:
2313 suffix += 1
2314 change_id = f"{base}-{suffix}"
2315 self.ensure_resp_stmt(RDGAI_RESP, "rdgai", "automatic classification")
2316 change = ET.SubElement(
2317 revision_desc,
2318 tei_tag(revision_desc, "change"),
2319 attrib={XML_ID: change_id, "when": now.isoformat().replace("+00:00", "Z"), "who": f"#{RDGAI_RESP}"},
2320 )
2321 change.text = (description.strip() + " " if description.strip() else "") + "Classification by rdgai using "
2322 model_name = ET.SubElement(change, tei_tag(revision_desc, "name"), attrib={"type": "model"})
2323 model_name.text = model
2324 model_name.tail = "."
2325 self.save()
2326 return change_id
2328 # -- suggestions -------------------------------------------------------------------
2330 @staticmethod
2331 def parse_source(source:str) -> tuple[str, str]:
2332 match = SOURCE.match((source or "").strip().lstrip("#"))
2333 if not match:
2334 raise AnnotationError(
2335 f"Invalid source '{source}': use a name such as 'claude', optionally with a model, e.g. 'rdgai:gpt-4o'."
2336 )
2337 return match["name"], match["model"] or ""
2339 def suggestion_list(self, app:App, create:bool=False):
2340 list_relation = find_element(app.element, ".//listRelation[@type='suggestion']")
2341 if list_relation is None and create:
2342 note = ET.SubElement(app.element, tei_tag(app.element, "note"))
2343 list_relation = ET.SubElement(note, tei_tag(app.element, "listRelation"), attrib={"type": "suggestion"})
2344 return list_relation
2346 def suggestion_relations(self, app:App) -> list:
2347 list_relation = self.suggestion_list(app)
2348 if list_relation is None:
2349 return []
2350 return unique(find_elements(list_relation, "./relation"))
2352 def suggestion_info(self, app:App, relation) -> SuggestionInfo:
2353 provenance = self.provenance_from_relation(relation)
2354 name = provenance.resp.lstrip("#")
2355 return SuggestionInfo(
2356 unit_id=str(app),
2357 active=relation.get("active"),
2358 passive=relation.get("passive"),
2359 category=" ".join(token.lstrip("#") for token in relation.get("ana", "").split()),
2360 source=f"{name}:{provenance.model}" if provenance.model else name,
2361 model=provenance.model,
2362 justification=provenance.justification,
2363 cert=provenance.cert,
2364 when=provenance.when,
2365 definitions_hash=provenance.definitions_hash,
2366 )
2368 def remove_suggestion_relations(self, app:App, readings:set[str], source:str|None=None):
2369 for relation in self.suggestion_relations(app):
2370 if {relation.get("active"), relation.get("passive")} != readings:
2371 continue
2372 if source is not None and self.suggestion_info(app, relation).source != source:
2373 continue
2374 relation.getparent().remove(relation)
2375 list_relation = self.suggestion_list(app)
2376 if list_relation is not None and len(list_relation) == 0:
2377 note = list_relation.getparent()
2378 note.remove(list_relation)
2379 if len(note) == 0 and not (note.text or "").strip():
2380 note.getparent().remove(note)
2382 def suggest_classification(
2383 self,
2384 unit_id:str,
2385 active:str,
2386 passive:str,
2387 category:str,
2388 justification:str="",
2389 source:str="claude",
2390 cert:str|None=None,
2391 change:str|None=None,
2392 allow_test_unit:bool=False,
2393 ) -> SuggestionResult:
2394 """
2395 Records a suggested category for the change from the active to the passive reading (and the inverse
2396 for the reverse pair). Suggestions are kept in <listRelation type="suggestion">, separate from labels,
2397 and replace earlier suggestions from the same source for the pair.
2399 Suggestions on the sample's test units are refused unless allow_test_unit (they would leak into the
2400 evaluation); in evaluation mode they are always refused.
2401 """
2402 with self.writing():
2403 self.check_writable()
2404 self.refresh()
2405 name, model = self.parse_source(source)
2406 source = f"{name}:{model}" if model else name
2407 self.check_cert(cert, optional=True)
2408 app = self.get_app(unit_id)
2409 self.check_unit_writable(app)
2410 if self.sample_role(str(app)) == "test" and not allow_test_unit:
2411 raise AnnotationError(
2412 f"{app} is a test unit: suggestions there would leak into the evaluation. "
2413 "Pass allow_test_unit to make one anyway."
2414 )
2415 pair = self.get_pair(app, active, passive)
2416 relation_type = self.get_relation_type(category)
2418 if name == RDGAI_RESP:
2419 self.ensure_resp_stmt(RDGAI_RESP, "rdgai", "automatic classification")
2420 elif name == "claude":
2421 self.ensure_resp_stmt("claude", "Claude", "suggested classifications")
2422 else:
2423 self.ensure_resp_stmt(name, name, "suggested classifications")
2425 self.remove_suggestion_relations(app, {active, passive}, source=source)
2426 change_attr = self.change_pointers(change, self.ensure_model_change(model) if model else None, self.ensure_definitions_change())
2427 when = self.now()
2428 justification = (justification or "").strip()
2429 list_relation = self.suggestion_list(app, create=True)
2430 created = []
2431 for (first, second, relation_type_, text) in (
2432 (active, passive, relation_type, justification),
2433 (passive, active, relation_type.get_inverse(), f"Inverse of {active} → {passive}: {justification}" if justification else ""),
2434 ):
2435 attrib = {"active": first, "passive": second, "ana": f"#{relation_type_.name}", "resp": f"#{name}"}
2436 if cert:
2437 attrib["cert"] = cert
2438 attrib["change"] = change_attr
2439 relation = ET.SubElement(list_relation, tei_tag(list_relation, "relation"), attrib=attrib)
2440 desc = ET.SubElement(relation, tei_tag(relation, "desc"), attrib={"type": "justification"})
2441 desc.text = text or None
2442 ET.SubElement(desc, tei_tag(relation, "date"), attrib={"when": when})
2443 created.append(relation)
2444 self.save()
2445 return SuggestionResult(
2446 unit_id=str(app),
2447 suggestion=self.suggestion_info(app, created[0]),
2448 inverse=self.suggestion_info(app, created[1]),
2449 )
2451 def get_suggestions(
2452 self,
2453 unit_id:str|None=None,
2454 active:str|None=None,
2455 passive:str|None=None,
2456 source:str|None=None,
2457 ) -> list[SuggestionInfo]:
2458 """
2459 Returns suggestions, optionally for one unit, one pair (in the direction given) and/or one source.
2460 Without a pair, each suggestion is given once, for the pair in document order.
2461 """
2462 with self.lock:
2463 self.refresh()
2464 apps = [self.get_app(unit_id)] if unit_id else self.doc.apps
2465 apps = [app for app in apps if not self.hides(app)]
2466 if source is not None:
2467 name, model = self.parse_source(source)
2468 source = f"{name}:{model}" if model else name
2469 results = []
2470 for app in apps:
2471 order = {reading.n: index for index, reading in enumerate(app.readings)}
2472 for relation in self.suggestion_relations(app):
2473 first, second = relation.get("active"), relation.get("passive")
2474 if active is not None or passive is not None:
2475 if (first, second) != (active, passive):
2476 continue
2477 elif order.get(first, 0) > order.get(second, 0):
2478 continue
2479 info = self.suggestion_info(app, relation)
2480 if source is not None and info.source != source:
2481 continue
2482 results.append(info)
2483 return results
2485 def suggestions_for(self, app:App, pair:Pair) -> list[SuggestionInfo]:
2486 """ Suggestions for a pair in its direction (no file refresh; for use while rendering a unit). """
2487 if self.hides(app):
2488 return []
2489 return [
2490 self.suggestion_info(app, relation) for relation in self.suggestion_relations(app)
2491 if (relation.get("active"), relation.get("passive")) == (pair.active.n, pair.passive.n)
2492 ]
2494 def clear_suggestions(self, unit_id:str, active:str, passive:str, source:str|None=None):
2495 """ Removes the suggestions for a pair (both directions), from one source or from all. """
2496 with self.writing():
2497 self.check_writable()
2498 self.refresh()
2499 app = self.get_app(unit_id)
2500 self.check_unit_writable(app)
2501 self.get_pair(app, active, passive)
2502 if source is not None:
2503 name, model = self.parse_source(source)
2504 source = f"{name}:{model}" if model else name
2505 self.remove_suggestion_relations(app, {active, passive}, source=source)
2506 self.save()