Spaces:
Sleeping
Sleeping
File size: 15,804 Bytes
2b83d93 979f3c3 2b83d93 | 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 | """Tests Sprint 63 โ banc d'essai de pipelines composรฉes (axe B).
Couvre :
1. ``PipelineSpec.validate`` : pipeline vide, types qui s'enchaรฎnent,
manque d'entrรฉe ร une รฉtape.
2. ``PipelineRunner.run`` :
- 1 รฉtape OCR mock + GT TEXT โ mรฉtriques calculรฉes ร la jonction
- 2 รฉtapes OCR + rewriter LLM mock โ 2 jonctions รฉvaluรฉes
- Module qui lรจve โ propagation gracieuse, รฉtapes suivantes
reรงoivent une erreur explicite d'entrรฉe manquante
- Sortie dรฉclarรฉe mais non produite โ erreur explicite
- Aucune GT au type produit โ pas de mรฉtriques (pas d'erreur)
- Mesure du temps par รฉtape > 0
3. Cas d'usage rรฉaliste : OCR fautif + rewriter qui corrige โ la
mรฉtrique CER baisse ร la jonction post-rewrite.
4. ``PipelineResult.junction_metrics_for`` retourne les mรฉtriques
de la derniรจre รฉtape ayant produit le type, ignorant les รฉtapes
qui ont รฉchouรฉ.
5. **Test philosophie** : Picarones ne fournit pas de modules
mรฉtier โ tous les modules utilisรฉs ici sont des **mocks dรฉfinis
dans le test**, pas dans le code de production.
"""
from __future__ import annotations
from typing import Any
from picarones.core.corpus import Document, GTLevel, TextGT
from picarones.core.modules import ArtifactType, BaseModule
from picarones.core.pipeline import (
PipelineResult,
PipelineRunner,
PipelineSpec,
PipelineStep,
StepResult,
)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# Mocks โ uniquement ร but de test, jamais en production
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class MockOCR(BaseModule):
"""Mock d'un OCR : produit un texte fixe ร partir d'une image."""
input_types = (ArtifactType.IMAGE,)
output_types = (ArtifactType.TEXT,)
execution_mode: Any = "io"
def __init__(self, fixed_output: str) -> None:
self._out = fixed_output
@property
def name(self) -> str:
return "mock-ocr"
def process(self, inputs: dict[ArtifactType, Any]) -> dict[ArtifactType, Any]:
return {ArtifactType.TEXT: self._out}
class MockTextRewriter(BaseModule):
"""Mock d'un correcteur LLM TEXTโTEXT."""
input_types = (ArtifactType.TEXT,)
output_types = (ArtifactType.TEXT,)
execution_mode: Any = "cpu"
def __init__(self, transform) -> None:
self._transform = transform
@property
def name(self) -> str:
return "mock-rewriter"
def process(self, inputs: dict[ArtifactType, Any]) -> dict[ArtifactType, Any]:
return {ArtifactType.TEXT: self._transform(inputs[ArtifactType.TEXT])}
class MockCrasher(BaseModule):
"""Mock d'un module qui lรจve ร chaque appel."""
input_types = (ArtifactType.TEXT,)
output_types = (ArtifactType.TEXT,)
execution_mode: Any = "cpu"
@property
def name(self) -> str:
return "mock-crasher"
def process(self, inputs: dict[ArtifactType, Any]) -> dict[ArtifactType, Any]:
raise RuntimeError("module en panne")
class MockSilentDropper(BaseModule):
"""Mock d'un module qui dรฉclare produire TEXT mais ne le produit pas."""
input_types = (ArtifactType.TEXT,)
output_types = (ArtifactType.TEXT,)
execution_mode: Any = "cpu"
@property
def name(self) -> str:
return "mock-silent-dropper"
def process(self, inputs: dict[ArtifactType, Any]) -> dict[ArtifactType, Any]:
return {}
def _make_doc(
text: str = "hello world", with_gt: bool = True,
) -> Document:
gts: dict[GTLevel, Any] = {}
if with_gt:
gts[GTLevel.TEXT] = TextGT(text=text)
return Document(
image_path="/tmp/x.png",
ground_truth=text if with_gt else "",
doc_id="d1",
ground_truths=gts,
)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 1. PipelineSpec.validate
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class TestSpecValidate:
def test_empty_pipeline_invalid(self) -> None:
spec = PipelineSpec(name="empty")
problems = spec.validate(initial_inputs=(ArtifactType.IMAGE,))
assert problems
assert "vide" in problems[0]
def test_single_step_with_image_input_valid(self) -> None:
spec = PipelineSpec(
name="ocr",
steps=[PipelineStep("ocr", MockOCR("x"))],
)
assert spec.is_valid((ArtifactType.IMAGE,))
def test_chained_steps_valid(self) -> None:
spec = PipelineSpec(
name="ocr_then_rewrite",
steps=[
PipelineStep("ocr", MockOCR("x")),
PipelineStep("rewrite", MockTextRewriter(lambda t: t)),
],
)
assert spec.is_valid((ArtifactType.IMAGE,))
def test_missing_input_invalid(self) -> None:
# Rewriter demande TEXT mais aucun OCR n'a รฉtรฉ placรฉ avant
spec = PipelineSpec(
name="rewrite_only",
steps=[PipelineStep("rewrite", MockTextRewriter(lambda t: t))],
)
problems = spec.validate(initial_inputs=(ArtifactType.IMAGE,))
assert problems
assert "rewrite" in problems[0]
assert "text" in problems[0]
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 2. PipelineRunner.run โ chemins nominaux
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class TestRunSingleStep:
def test_one_step_with_text_gt(self) -> None:
doc = _make_doc("hello world")
spec = PipelineSpec(
name="ocr",
steps=[PipelineStep("ocr", MockOCR("hello world"))],
)
result = PipelineRunner.run(
spec, doc, {ArtifactType.IMAGE: "/tmp/x.png"},
)
assert result.succeeded
assert len(result.steps) == 1
step = result.steps[0]
assert step.error is None
assert step.duration_seconds >= 0.0
# Mรฉtrique CER ร 0 (hyp == GT)
assert step.junction_metrics["text"]["cer"] == 0.0
def test_one_step_imperfect_ocr(self) -> None:
doc = _make_doc("hello world")
spec = PipelineSpec(
name="ocr",
steps=[PipelineStep("ocr", MockOCR("hellp wrld"))],
)
result = PipelineRunner.run(
spec, doc, {ArtifactType.IMAGE: "/tmp/x.png"},
)
cer = result.steps[0].junction_metrics["text"]["cer"]
assert 0.0 < cer < 1.0
class TestRunChained:
def test_two_steps_evaluation_at_each_junction(self) -> None:
doc = _make_doc("hello world")
# OCR fautif + rewriter qui corrige
spec = PipelineSpec(
name="ocr_then_rewrite",
steps=[
PipelineStep("ocr", MockOCR("hello wrold")),
PipelineStep(
"rewrite",
MockTextRewriter(lambda t: t.replace("wrold", "world")),
),
],
)
result = PipelineRunner.run(
spec, doc, {ArtifactType.IMAGE: "/tmp/x.png"},
)
assert result.succeeded
assert len(result.steps) == 2
cer_after_ocr = result.steps[0].junction_metrics["text"]["cer"]
cer_after_rewrite = result.steps[1].junction_metrics["text"]["cer"]
# Le CER baisse aprรจs le rewriter
assert cer_after_rewrite < cer_after_ocr
assert cer_after_rewrite == 0.0
def test_junction_metrics_for_returns_last(self) -> None:
doc = _make_doc("hello world")
spec = PipelineSpec(
name="ocr_then_rewrite",
steps=[
PipelineStep("ocr", MockOCR("hello wrold")),
PipelineStep(
"rewrite",
MockTextRewriter(lambda t: t.replace("wrold", "world")),
),
],
)
result = PipelineRunner.run(
spec, doc, {ArtifactType.IMAGE: "/tmp/x.png"},
)
final = result.junction_metrics_for(ArtifactType.TEXT)
assert final is not None
assert final["cer"] == 0.0
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 3. Erreurs gracieuses
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class TestGracefulErrors:
def test_module_raises_captured(self) -> None:
doc = _make_doc("hello world")
spec = PipelineSpec(
name="crash",
steps=[
PipelineStep("ocr", MockOCR("hello world")),
PipelineStep("crash", MockCrasher()),
],
)
result = PipelineRunner.run(
spec, doc, {ArtifactType.IMAGE: "/tmp/x.png"},
)
assert not result.succeeded
assert result.steps[1].error is not None
assert "RuntimeError" in result.steps[1].error
assert "panne" in result.steps[1].error
# L'รฉtape prรฉcรฉdente reste OK
assert result.steps[0].error is None
assert result.failing_steps == ["crash"]
def test_silent_dropper_reported_as_missing_output(self) -> None:
doc = _make_doc("hello world")
spec = PipelineSpec(
name="dropper",
steps=[
PipelineStep("ocr", MockOCR("hello world")),
PipelineStep("drop", MockSilentDropper()),
],
)
result = PipelineRunner.run(
spec, doc, {ArtifactType.IMAGE: "/tmp/x.png"},
)
# L'รฉtape drop signale une sortie manquante
assert result.steps[1].error is not None
assert "sortie manquante" in result.steps[1].error
def test_invalid_spec_marked_as_error(self) -> None:
doc = _make_doc()
# Pipeline qui demande TEXT mais on ne fournit que IMAGE
# et aucun OCR ne prรฉcรจde
spec = PipelineSpec(
name="bad",
steps=[PipelineStep("rewrite", MockTextRewriter(lambda t: t))],
)
result = PipelineRunner.run(
spec, doc, {ArtifactType.IMAGE: "/tmp/x.png"},
)
assert result.error is not None
assert "text" in result.error
# Aucune รฉtape n'a รฉtรฉ exรฉcutรฉe
assert result.steps == []
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 4. Pas de GT โ pas de mรฉtriques mais pas d'erreur
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class TestNoGroundTruth:
def test_no_gt_no_metrics_no_error(self) -> None:
doc = _make_doc(with_gt=False)
spec = PipelineSpec(
name="ocr",
steps=[PipelineStep("ocr", MockOCR("anything"))],
)
result = PipelineRunner.run(
spec, doc, {ArtifactType.IMAGE: "/tmp/x.png"},
)
# Pas d'erreur โ la pipeline a tournรฉ, simplement aucune
# mรฉtrique calculable
# (Document __post_init__ crรฉe TextGT depuis ground_truth=""
# donc une GT vide existe ; la mรฉtrique CER vaudra alors 1.0
# ce qui est un autre test ; pour ce test on retire la GT.)
# On accepte donc soit absence soit prรฉsence du dict junction_metrics ;
# le point clรฉ est que รงa ne plante pas.
assert result.steps[0].error is None
assert result.succeeded
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 5. Temps par รฉtape
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class TestTiming:
def test_step_duration_recorded(self) -> None:
doc = _make_doc()
spec = PipelineSpec(
name="ocr",
steps=[PipelineStep("ocr", MockOCR("hello"))],
)
result = PipelineRunner.run(
spec, doc, {ArtifactType.IMAGE: "/tmp/x.png"},
)
assert result.steps[0].duration_seconds >= 0.0
assert result.total_duration_seconds >= result.steps[0].duration_seconds
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 6. Dataclasses (StepResult / PipelineResult)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class TestDataclasses:
def test_step_result_default(self) -> None:
sr = StepResult(
step_name="x", duration_seconds=0.1, output_types=(),
)
assert sr.junction_metrics == {}
assert sr.error is None
def test_pipeline_result_succeeded_false_on_step_error(self) -> None:
pr = PipelineResult(
pipeline_name="p", doc_id="d",
steps=[
StepResult(step_name="a", duration_seconds=0.1,
output_types=(ArtifactType.TEXT,)),
StepResult(step_name="b", duration_seconds=0.1,
output_types=(), error="boom"),
],
)
assert not pr.succeeded
assert pr.failing_steps == ["b"]
def test_junction_metrics_for_skips_failed_steps(self) -> None:
# รtape 1 a รฉchouรฉ, รฉtape 0 a produit TEXT avec une mรฉtrique
pr = PipelineResult(
pipeline_name="p", doc_id="d",
steps=[
StepResult(
step_name="ocr", duration_seconds=0.1,
output_types=(ArtifactType.TEXT,),
junction_metrics={"text": {"cer": 0.1}},
),
StepResult(
step_name="rewrite", duration_seconds=0.1,
output_types=(), error="boom",
),
],
)
# On doit retomber sur l'รฉtape OCR (la derniรจre qui a rรฉussi
# pour TEXT)
assert pr.junction_metrics_for(ArtifactType.TEXT) == {"cer": 0.1}
|