Spaces:
Running
Running
File size: 21,372 Bytes
874134a 2e9e564 874134a fb1d823 874134a fb1d823 874134a fb1d823 874134a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 | """Sprint A14-S17 โ run complet avec persistance JSONL.
Dรฉfinition de done : un benchmark produit un dossier ``result/``
lisible humainement oรน on voit :
- ``run_manifest.json`` โ mรฉtadonnรฉes (run_id, corpus, pipelines,
vues, code_version, timestamps).
- ``pipeline_results.jsonl`` โ un PipelineResult par ligne avec
document_id.
- ``view_results.jsonl`` โ un ViewResult par ligne avec
document_id.
Le test exรฉcute :
- 2 pipelines mock (un OCR pur RAW_TEXT, un OCR+ALTO).
- 3 documents synthรฉtiques.
- 2 vues canoniques (TextView + AltoView โ SearchView est testรฉe
sรฉparรฉment en S16).
- Persistance dans tmp_path.
- Vรฉrification des fichiers produits + structure du RunResult.
Setup disque
------------
Le ``AltoToText`` projecteur (S9) lit son XML depuis l'``Artifact.uri``
filesystem. La fixture รฉcrit donc des fichiers ALTO XML rรฉels sur
disque sous ``tmp_path/alto_files/`` et les stubs OCR pointent leurs
artefacts ALTO vers ces fichiers via leur URI. Cela reproduit
l'usage production oรน un moteur รฉcrit son XML dans un workspace
sandboxรฉ (S19).
"""
from __future__ import annotations
import json
from pathlib import Path
from picarones.app.services import BenchmarkService
from picarones.domain import (
Artifact,
ArtifactType,
CorpusSpec,
DocumentRef,
GroundTruthRef,
MetricSpec,
)
from picarones.evaluation.metrics.alto_structural import (
compute_alto_validity,
compute_line_count_ratio,
compute_word_box_coverage,
)
from picarones.evaluation.projectors import (
AltoToText,
CanonicalToText,
PageToText,
ProjectorRegistry,
)
from picarones.evaluation.registry import MetricRegistry
from picarones.evaluation.views import (
DefaultEvaluationViewExecutor,
build_alto_view,
build_text_view,
)
from picarones.formats.alto.types import (
AltoBBox,
AltoDocument,
AltoLine,
AltoPage,
AltoString,
AltoTextBlock,
)
from picarones.formats.alto.writer import write_alto
from picarones.pipeline import (
CorpusRunner,
PipelineExecutor,
PipelineSpec,
PipelineStep,
RunContext,
)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# Fixtures de donnรฉes
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
_GT_TEXTS = {
"doc01": "Bonjour le monde",
"doc02": "Test multi documents",
"doc03": "Troisiรจme fixture",
}
def _build_alto(text: str) -> AltoDocument:
"""Produit un AltoDocument 1 page / 1 bloc / 1 ligne avec bbox
sur chaque mot."""
return AltoDocument(pages=(AltoPage(blocks=(AltoTextBlock(lines=(AltoLine(strings=tuple(
AltoString(content=w, bbox=AltoBBox(hpos=0, vpos=0, width=10, height=10))
for w in text.split()
)),),),),),),)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# Adapters / pipelines mock
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class _TextOCRStub:
"""OCR mock qui produit RAW_TEXT dรฉterministe."""
name = "text_ocr"
input_types = frozenset({ArtifactType.IMAGE})
output_types = frozenset({ArtifactType.RAW_TEXT})
execution_mode = "io"
def execute(self, inputs, params, context):
return {
ArtifactType.RAW_TEXT: Artifact(
id=f"{context.document_id}:text_ocr:raw_text",
document_id=context.document_id,
type=ArtifactType.RAW_TEXT,
produced_by_step="ocr",
),
}
class _AltoOCRStub:
"""OCR mock qui produit ALTO_XML + RAW_TEXT dรฉterministes.
Les fichiers ALTO sont supposรฉs dรฉjร prรฉsents sur disque dans
``alto_files_dir`` (รฉcrits par la fixture). L'artefact ALTO
pointe sa ``uri`` vers ce fichier โ pour reproduire la chaรฎne
de production oรน un moteur ALTO รฉcrit son XML dans un workspace
et l'expose via URI.
"""
name = "alto_ocr"
input_types = frozenset({ArtifactType.IMAGE})
output_types = frozenset({ArtifactType.ALTO_XML, ArtifactType.RAW_TEXT})
execution_mode = "io"
def __init__(self, alto_files_dir: Path) -> None:
self._alto_files_dir = Path(alto_files_dir)
def execute(self, inputs, params, context):
alto_path = self._alto_files_dir / f"{context.document_id}.cand.alto.xml"
return {
ArtifactType.ALTO_XML: Artifact(
id=f"{context.document_id}:alto_ocr:alto",
document_id=context.document_id,
type=ArtifactType.ALTO_XML,
produced_by_step="ocr",
uri=str(alto_path),
),
ArtifactType.RAW_TEXT: Artifact(
id=f"{context.document_id}:alto_ocr:raw_text",
document_id=context.document_id,
type=ArtifactType.RAW_TEXT,
produced_by_step="ocr",
),
}
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# Helpers
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def _stub_cer(reference: str, hypothesis: str) -> float:
if not reference:
return 0.0 if not hypothesis else 1.0
common = sum(1 for a, b in zip(reference, hypothesis) if a == b)
return 1.0 - (common / max(len(reference), len(hypothesis)))
def _stub_wer(reference: str, hypothesis: str) -> float:
rw = reference.split()
hw = hypothesis.split()
if not rw:
return 0.0 if not hw else 1.0
common = sum(1 for a, b in zip(rw, hw) if a == b)
return 1.0 - (common / len(rw))
def _write_alto_files(tmp_path: Path) -> tuple[Path, dict[str, Path], dict[str, Path]]:
"""รcrit GT et candidate ALTO XML sur disque pour chaque doc.
Returns
-------
(alto_dir, gt_paths_by_doc, cand_paths_by_doc)
"""
alto_dir = tmp_path / "alto_files"
alto_dir.mkdir(parents=True, exist_ok=True)
gt_paths: dict[str, Path] = {}
cand_paths: dict[str, Path] = {}
for doc_id, text in _GT_TEXTS.items():
gt_doc = _build_alto(text)
cand_doc = _build_alto(text) # Texte parfait โ ALTO identique.
gt_path = alto_dir / f"{doc_id}.gt.alto.xml"
cand_path = alto_dir / f"{doc_id}.cand.alto.xml"
gt_path.write_bytes(write_alto(gt_doc))
cand_path.write_bytes(write_alto(cand_doc))
gt_paths[doc_id] = gt_path
cand_paths[doc_id] = cand_path
return alto_dir, gt_paths, cand_paths
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# Setup complet (param tmp_path)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def _build_service(tmp_path: Path) -> tuple[BenchmarkService, dict[str, Path]]:
"""Construit le BenchmarkService avec fixtures sur disque.
Returns
-------
(service, gt_paths_by_doc)
"""
alto_dir, gt_paths, _cand_paths = _write_alto_files(tmp_path)
# Mรฉtriques (TextView + AltoView)
metrics = MetricRegistry()
for name, fn in (
("cer", _stub_cer),
("wer", _stub_wer),
("mer", _stub_cer),
("wil", _stub_wer),
):
metrics.register(
MetricSpec(
name=name,
input_types=(ArtifactType.RAW_TEXT, ArtifactType.RAW_TEXT),
),
fn,
)
for name, fn in (
("alto_validity", compute_alto_validity),
("alto_line_count_ratio", compute_line_count_ratio),
("alto_word_box_coverage", compute_word_box_coverage),
):
metrics.register(
MetricSpec(
name=name,
input_types=(ArtifactType.ALTO_XML, ArtifactType.ALTO_XML),
higher_is_better=True,
),
fn,
)
# Projecteurs
projectors = ProjectorRegistry()
projectors.register(AltoToText())
projectors.register(PageToText())
projectors.register(CanonicalToText())
# Loader hybride :
# - pour les RAW_TEXT directs (id se termine par ":raw_text") on
# retourne le texte parfait depuis _GT_TEXTS.
# - pour les artefacts projetรฉs (id se termine par ":projected_text")
# on retourne aussi le texte parfait (la projection a dรฉjร fait
# son travail en lisant le XML disque).
# - pour les ALTO_XML (GT ou candidat), on parse le fichier disque.
from picarones.formats.alto.parser import parse_alto
def loader(art: Artifact):
if art.type == ArtifactType.RAW_TEXT:
# GT ou candidat texte direct, ou rรฉsultat de projection.
return _GT_TEXTS[art.document_id]
if art.type == ArtifactType.ALTO_XML:
if art.uri is None:
raise KeyError(f"ALTO artefact {art.id} sans URI")
return parse_alto(Path(art.uri).read_bytes())
raise KeyError(f"loader ne sait pas charger {art.id} (type {art.type})")
view_executor = DefaultEvaluationViewExecutor.from_registries(
metrics, projectors, loader,
)
# Pipeline executor + corpus runner.
registry_adapters = {
"text_ocr": _TextOCRStub(),
"alto_ocr": _AltoOCRStub(alto_dir),
}
pipeline_executor = PipelineExecutor(
adapter_resolver=lambda n: registry_adapters[n],
)
corpus_runner = CorpusRunner(
pipeline_executor,
max_in_flight=2,
timeout_seconds_per_doc=10.0,
poll_interval_seconds=0.005,
)
service = BenchmarkService(
corpus_runner=corpus_runner,
view_executor=view_executor,
code_version="1.0.0-s17-test",
)
return service, gt_paths
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# Tests
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def _build_corpus_and_specs(gt_paths: dict[str, Path]):
# Note : ``image_uri`` et le ``uri`` de la GT RAW_TEXT ne sont
# jamais lus dans S17 (les payloads sont fournis in-memory par le
# loader des stubs). On les construit comme des chemins **sous le
# tmp_path partagรฉ** pour rester portable cross-OS โ sur Windows
# ``/tmp/...`` n'est pas un chemin absolu valide.
base_dir = next(iter(gt_paths.values())).parent
docs = tuple(
DocumentRef(
id=doc_id,
image_uri=str(base_dir / f"{doc_id}.png"),
ground_truths=(
GroundTruthRef(
type=ArtifactType.RAW_TEXT,
uri=str(base_dir / f"{doc_id}.gt.txt"),
),
GroundTruthRef(
type=ArtifactType.ALTO_XML,
uri=str(gt_paths[doc_id]),
),
),
)
for doc_id in _GT_TEXTS
)
corpus = CorpusSpec(name="s17_fixture", documents=docs)
text_pipeline = PipelineSpec(
name="text_only_pipeline",
initial_inputs=(ArtifactType.IMAGE,),
steps=(PipelineStep(
id="ocr", kind="ocr", adapter_name="text_ocr",
input_types=(ArtifactType.IMAGE,),
output_types=(ArtifactType.RAW_TEXT,),
),),
)
alto_pipeline = PipelineSpec(
name="alto_pipeline",
initial_inputs=(ArtifactType.IMAGE,),
steps=(PipelineStep(
id="ocr", kind="ocr", adapter_name="alto_ocr",
input_types=(ArtifactType.IMAGE,),
output_types=(ArtifactType.ALTO_XML, ArtifactType.RAW_TEXT),
),),
)
views = (build_text_view(), build_alto_view())
return corpus, [text_pipeline, alto_pipeline], list(views)
def _build_factories(gt_paths: dict[str, Path]):
def gt_factory(doc, art_type):
gt_ref = doc.gt_for(art_type)
if gt_ref is None:
return None
return Artifact(
id=f"{doc.id}:gt:{'raw_text' if art_type == ArtifactType.RAW_TEXT else 'alto'}",
document_id=doc.id,
type=art_type,
uri=gt_ref.uri,
)
def inputs_factory(doc):
return {ArtifactType.IMAGE: Artifact(
id=f"{doc.id}:image", document_id=doc.id,
type=ArtifactType.IMAGE, uri=doc.image_uri,
)}
def ctx_factory(doc, pipeline_name):
return RunContext(
document_id=doc.id,
code_version="1.0.0-s17-test",
pipeline_name=pipeline_name,
)
return gt_factory, inputs_factory, ctx_factory
class TestFullRun:
def test_run_produces_pipeline_results_for_each_doc(self, tmp_path: Path) -> None:
service, gt_paths = _build_service(tmp_path)
corpus, pipelines, views = _build_corpus_and_specs(gt_paths)
gt_factory, inputs_factory, ctx_factory = _build_factories(gt_paths)
result = service.run(
corpus=corpus,
pipelines=pipelines,
views=views,
ground_truth_factory=gt_factory,
pipeline_inputs_factory=inputs_factory,
context_factory=ctx_factory,
)
assert result.n_documents == 3
for doc_result in result.document_results:
assert len(doc_result.pipeline_results) == 2
pipeline_names = {pr.pipeline_name for pr in doc_result.pipeline_results}
assert pipeline_names == {"text_only_pipeline", "alto_pipeline"}
def test_omission_pattern_textview_includes_both_pipelines(self, tmp_path: Path) -> None:
"""TextView accepte RAW_TEXT et ALTO_XML โ les 2 pipelines
sont รฉligibles."""
service, gt_paths = _build_service(tmp_path)
corpus, pipelines, views = _build_corpus_and_specs(gt_paths)
gt_factory, inputs_factory, ctx_factory = _build_factories(gt_paths)
result = service.run(
corpus=corpus,
pipelines=pipelines,
views=views,
ground_truth_factory=gt_factory,
pipeline_inputs_factory=inputs_factory,
context_factory=ctx_factory,
)
text_view_results = result.view_results_for("text_final")
# text_only_pipeline produit RAW_TEXT (1 รฉligible).
# alto_pipeline produit RAW_TEXT + ALTO_XML (2 รฉligibles).
# Total : 3 docs ร (1 + 2) = 9 ViewResult.
assert len(text_view_results) == 9
for vr in text_view_results:
assert vr.view_name == "text_final"
def test_omission_pattern_altoview_omits_text_only_pipeline(self, tmp_path: Path) -> None:
"""AltoView n'accepte qu'ALTO_XML โ text_only_pipeline OMIS."""
service, gt_paths = _build_service(tmp_path)
corpus, pipelines, views = _build_corpus_and_specs(gt_paths)
gt_factory, inputs_factory, ctx_factory = _build_factories(gt_paths)
result = service.run(
corpus=corpus,
pipelines=pipelines,
views=views,
ground_truth_factory=gt_factory,
pipeline_inputs_factory=inputs_factory,
context_factory=ctx_factory,
)
alto_view_results = result.view_results_for("alto_documentary")
# 3 docs ร 1 pipeline (alto_pipeline) ร 1 artefact ALTO = 3 results.
assert len(alto_view_results) == 3
for vr in alto_view_results:
assert "alto_ocr" in vr.candidate_artifact_id
def test_view_results_have_metric_values(self, tmp_path: Path) -> None:
service, gt_paths = _build_service(tmp_path)
corpus, pipelines, views = _build_corpus_and_specs(gt_paths)
gt_factory, inputs_factory, ctx_factory = _build_factories(gt_paths)
result = service.run(
corpus=corpus,
pipelines=pipelines,
views=views,
ground_truth_factory=gt_factory,
pipeline_inputs_factory=inputs_factory,
context_factory=ctx_factory,
)
for vr in result.view_results_for("text_final"):
# CER stub doit รชtre 0 (texte parfait dans la fixture).
assert vr.metric_values.get("cer") == 0.0
assert vr.failed_metrics == {}
class TestPersistence:
def test_persist_writes_three_files(self, tmp_path: Path) -> None:
service, gt_paths = _build_service(tmp_path)
corpus, pipelines, views = _build_corpus_and_specs(gt_paths)
gt_factory, inputs_factory, ctx_factory = _build_factories(gt_paths)
result = service.run(
corpus=corpus,
pipelines=pipelines,
views=views,
ground_truth_factory=gt_factory,
pipeline_inputs_factory=inputs_factory,
context_factory=ctx_factory,
)
out_dir = tmp_path / "run_output"
files = service.persist(result, out_dir)
assert files["manifest"].exists()
assert files["pipeline_results"].exists()
assert files["view_results"].exists()
def test_persisted_manifest_is_valid_json(self, tmp_path: Path) -> None:
service, gt_paths = _build_service(tmp_path)
corpus, pipelines, views = _build_corpus_and_specs(gt_paths)
gt_factory, inputs_factory, ctx_factory = _build_factories(gt_paths)
result = service.run(
corpus=corpus,
pipelines=pipelines,
views=views,
ground_truth_factory=gt_factory,
pipeline_inputs_factory=inputs_factory,
context_factory=ctx_factory,
)
out_dir = tmp_path / "run_output"
files = service.persist(result, out_dir)
manifest_data = json.loads(files["manifest"].read_text())
assert manifest_data["corpus_name"] == "s17_fixture"
assert manifest_data["n_documents"] == 3
assert manifest_data["code_version"] == "1.0.0-s17-test"
assert "text_only_pipeline" in manifest_data["pipeline_names"]
assert "alto_pipeline" in manifest_data["pipeline_names"]
def test_persisted_jsonl_is_streamable(self, tmp_path: Path) -> None:
"""Chaque ligne de pipeline_results.jsonl et view_results.jsonl
est un JSON valide indรฉpendamment (streaming)."""
service, gt_paths = _build_service(tmp_path)
corpus, pipelines, views = _build_corpus_and_specs(gt_paths)
gt_factory, inputs_factory, ctx_factory = _build_factories(gt_paths)
result = service.run(
corpus=corpus,
pipelines=pipelines,
views=views,
ground_truth_factory=gt_factory,
pipeline_inputs_factory=inputs_factory,
context_factory=ctx_factory,
)
files = service.persist(result, tmp_path / "out")
# pipeline_results.jsonl : 3 docs ร 2 pipelines = 6 lignes.
pipeline_lines = files["pipeline_results"].read_text().strip().split("\n")
assert len(pipeline_lines) == 6
for line in pipeline_lines:
payload = json.loads(line)
assert "document_id" in payload
assert "pipeline_name" in payload
# view_results.jsonl : 9 (TextView) + 3 (AltoView) = 12 lignes.
view_lines = files["view_results"].read_text().strip().split("\n")
assert len(view_lines) == 12
for line in view_lines:
payload = json.loads(line)
assert "document_id" in payload
assert "view_name" in payload
assert "metric_values" in payload
class TestRunResultHelpers:
def test_pipeline_results_for_returns_correct_subset(self, tmp_path: Path) -> None:
service, gt_paths = _build_service(tmp_path)
corpus, pipelines, views = _build_corpus_and_specs(gt_paths)
gt_factory, inputs_factory, ctx_factory = _build_factories(gt_paths)
result = service.run(
corpus=corpus,
pipelines=pipelines,
views=views,
ground_truth_factory=gt_factory,
pipeline_inputs_factory=inputs_factory,
context_factory=ctx_factory,
)
# 3 docs ร 1 pipeline (filtrรฉ sur "text_only_pipeline").
text_results = result.pipeline_results_for("text_only_pipeline")
assert len(text_results) == 3
for pr in text_results:
assert pr.pipeline_name == "text_only_pipeline"
|