Spaces:
Sleeping
Sleeping
File size: 54,756 Bytes
5e48c0b bc96a54 5e48c0b bc96a54 5e48c0b fca122a 5e48c0b fca122a 5e48c0b fca122a 5e48c0b fca122a 5e48c0b bc96a54 dae1005 a2f768d e12723a da31b89 e12723a | 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 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 | """Phase 1 du chantier post-rewrite โ durcissements sรฉcuritรฉ P0.
Couvre trois durcissements introduits pour fermer des surfaces filesystem
laissรฉes ouvertes par le rewrite :
1. **Path traversal ``output_dir`` dans les importers HTR-United/HuggingFace.**
Avant durcissement : un POST ``output_dir="/etc/picarones_pwned"``
passait directement ร l'importer, vecteur d'รฉcriture filesystem
arbitraire. Dรฉsormais ``validated_path`` rejette en 400 avant dรฉlรฉgation.
2. **Path traversal ``db_path`` dans ``/api/history/regressions``.**
Avant durcissement : ``db_path=/etc/passwd`` ouvrait un SQLite
arbitraire (lecture libre, log d'erreur informatif). Dรฉsormais
``validated_path`` rejette en 400 ; pour pointer une base hors
workspace, exporter ``PICARONES_HISTORY_DB``.
3. **ZIP basename collision + validation image extraite.**
Avant durcissement : ``a/img.png`` et ``b/img.png`` s'รฉcrasaient
silencieusement aprรจs aplatissement ; les images extraites n'รฉtaient
pas passรฉes ร ``validate_image_safe`` (vecteur zip bomb jusqu'ร
500 Mo brut). Dรฉsormais : collision โ renommage avec prรฉfixe slug
du dirname + warning ; image invalide โ ``ValueError`` (HTTP 415).
"""
from __future__ import annotations
import io
import zipfile
from pathlib import Path
from unittest.mock import patch
import pytest
# PNG 1x1 minimal valide pour passer Pillow.verify.
_MINIMAL_PNG = (
b"\x89PNG\r\n\x1a\n"
b"\x00\x00\x00\rIHDR"
b"\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00"
b"\x1f\x15\xc4\x89"
b"\x00\x00\x00\nIDATx\x9cc\x00\x01\x00\x00\x05\x00\x01"
b"\r\n-\xb4\x00\x00\x00\x00IEND\xaeB`\x82"
)
def _make_importers_app():
from fastapi import FastAPI
from picarones.interfaces.web.routers import importers as imp_router
app = FastAPI()
app.include_router(imp_router.router)
return app
def _make_history_app():
from fastapi import FastAPI
from picarones.interfaces.web.routers import history as hist_router
app = FastAPI()
app.include_router(hist_router.router)
return app
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 1. output_dir path traversal โ HTR-United + HuggingFace
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class TestImportersOutputDirTraversal:
"""Aucun ``output_dir`` libre hors des racines workspace.
Important : on n'utilise PAS ``patch`` sur l'importer โ la validation
doit รฉchouer AVANT toute dรฉlรฉgation au backend. Si la validation
laisse passer, le mock ne sera pas appelรฉ mais la requรชte sera
acceptรฉe โ c'est ce qu'on doit empรชcher.
"""
def test_htr_united_rejects_absolute_path_outside_workspace(self) -> None:
from fastapi.testclient import TestClient
app = _make_importers_app()
with TestClient(app) as client:
r = client.post(
"/api/htr-united/import",
json={
"entry_id": "any_id",
"output_dir": "/etc/picarones_pwned",
"max_samples": 1,
},
)
# 400 = PathValidationError mappรฉe par le handler.
assert r.status_code == 400, (
f"Attendu 400 (path validation), reรงu {r.status_code} : "
f"{r.text}"
)
assert "hors zone autorisรฉe" in r.json()["detail"]
def test_htr_united_rejects_traversal(self) -> None:
from fastapi.testclient import TestClient
app = _make_importers_app()
with TestClient(app) as client:
r = client.post(
"/api/htr-united/import",
json={
"entry_id": "any_id",
"output_dir": "../../../etc/passwd",
"max_samples": 1,
},
)
assert r.status_code == 400
# Le message peut citer la racine ou le chemin original ;
# on vรฉrifie juste qu'on n'a pas rรฉussi ร passer.
detail = r.json()["detail"]
assert "hors zone" in detail or "invalide" in detail
def test_huggingface_rejects_absolute_path_outside_workspace(
self,
) -> None:
from fastapi.testclient import TestClient
app = _make_importers_app()
with TestClient(app) as client:
r = client.post(
"/api/huggingface/import",
json={
"dataset_id": "any/dataset",
"output_dir": "/var/lib/pwned",
"split": "train",
"max_samples": 1,
},
)
assert r.status_code == 400
assert "hors zone autorisรฉe" in r.json()["detail"]
def test_huggingface_rejects_traversal(self) -> None:
from fastapi.testclient import TestClient
app = _make_importers_app()
with TestClient(app) as client:
r = client.post(
"/api/huggingface/import",
json={
"dataset_id": "any/dataset",
"output_dir": "../../../etc/passwd_dir",
"split": "train",
"max_samples": 1,
},
)
assert r.status_code == 400
def test_huggingface_accepts_path_under_tmp(self, tmp_path: Path) -> None:
"""``tmp_path`` est sous ``tempfile.gettempdir()`` donc dans les
racines workspace par dรฉfaut (mode dev). On vรฉrifie que la
validation laisse passer une cible lรฉgitime."""
from fastapi.testclient import TestClient
app = _make_importers_app()
with patch(
"picarones.adapters.corpus.huggingface.HuggingFaceImporter.import_dataset",
) as mock_import:
mock_import.return_value = {
"imported": 1, "output_dir": str(tmp_path),
}
with TestClient(app) as client:
r = client.post(
"/api/huggingface/import",
json={
"dataset_id": "test/dataset",
"output_dir": str(tmp_path),
"split": "train",
"max_samples": 1,
},
)
assert r.status_code == 200, r.text
# Vรฉrifie que la valeur passรฉe ร l'importer est rรฉsolue
# (str du Path absolu) โ pas la chaรฎne brute si elle
# avait รฉtรฉ relative.
assert mock_import.called
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 2. db_path path traversal โ /api/history/regressions
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class TestHistoryRegressionsDbPathTraversal:
"""``db_path`` doit รชtre sous une racine workspace ou refusรฉ en 400.
Sans ce garde-fou, l'endpoint ouvrait silencieusement n'importe quel
SQLite lisible par le process (lecture filesystem arbitraire via
paramรจtres SQL).
"""
def test_absolute_path_outside_workspace_rejected(self) -> None:
from fastapi.testclient import TestClient
app = _make_history_app()
with TestClient(app) as client:
r = client.get(
"/api/history/regressions",
params={"db_path": "/etc/passwd"},
)
assert r.status_code == 400, r.text
assert "hors zone autorisรฉe" in r.json()["detail"]
def test_traversal_rejected(self) -> None:
from fastapi.testclient import TestClient
app = _make_history_app()
with TestClient(app) as client:
r = client.get(
"/api/history/regressions",
params={"db_path": "../../../etc/passwd"},
)
assert r.status_code == 400
def test_no_db_path_uses_default(self) -> None:
"""Sans ``db_path``, l'endpoint utilise le dรฉfaut ``BenchmarkHistory()``
(~/.picarones/history.db). Pas de 400, retourne une liste vide
si la base n'existe pas (cas frais)."""
from fastapi.testclient import TestClient
app = _make_history_app()
with TestClient(app) as client:
r = client.get("/api/history/regressions")
# Soit 200 (base existe, pas de rรฉgression), soit 500 (base
# absente). On accepte les deux โ c'est le comportement
# historique, hors scope du durcissement de chemin.
assert r.status_code in (200, 500), r.text
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 3. ZIP basename collision + validation image extraite
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def _zip_with_entries(entries: dict[str, bytes]) -> bytes:
"""ZIP en mรฉmoire ร partir de ``{nom: bytes}``."""
buf = io.BytesIO()
with zipfile.ZipFile(buf, mode="w", compression=zipfile.ZIP_DEFLATED) as zf:
for name, data in entries.items():
zf.writestr(name, data)
return buf.getvalue()
class TestZipBasenameCollision:
"""``a/img.png`` et ``b/img.png`` ne doivent plus s'รฉcraser
silencieusement aprรจs aplatissement par basename."""
def test_collision_resolved_with_dirname_prefix(self, tmp_path: Path) -> None:
from picarones.interfaces.web.corpus_utils import flatten_zip_to_dir
zip_bytes = _zip_with_entries({
"folder_a/page_001.png": _MINIMAL_PNG,
"folder_a/page_001.gt.txt": b"GT A",
"folder_b/page_001.png": _MINIMAL_PNG,
"folder_b/page_001.gt.txt": b"GT B",
})
dest = tmp_path / "extract"
with zipfile.ZipFile(io.BytesIO(zip_bytes)) as zf:
flatten_zip_to_dir(zf, dest)
names = {p.name for p in dest.iterdir()}
# La premiรจre occurrence garde le nom brut ; les suivantes sont
# prรฉfixรฉes par le slug du dirname source.
assert "page_001.png" in names
# Le second doit avoir รฉtรฉ renommรฉ โ par slug ``folder_b``.
renamed_png = {n for n in names if n.endswith("page_001.png")}
assert len(renamed_png) == 2, (
f"Attendu 2 images distinctes (1 nominale + 1 renommรฉe), "
f"trouvรฉ {renamed_png}"
)
# On vรฉrifie qu'au moins une variante porte un slug de dossier.
assert any(
"folder_a" in n or "folder_b" in n
for n in renamed_png - {"page_001.png"}
)
def test_no_silent_overwrite_of_image_pairs(self, tmp_path: Path) -> None:
"""Garantie fonctionnelle : 4 fichiers entrent โ 4 fichiers sortent."""
from picarones.interfaces.web.corpus_utils import flatten_zip_to_dir
zip_bytes = _zip_with_entries({
"a/img.png": _MINIMAL_PNG,
"a/img.gt.txt": b"A",
"b/img.png": _MINIMAL_PNG,
"b/img.gt.txt": b"B",
})
dest = tmp_path / "extract"
with zipfile.ZipFile(io.BytesIO(zip_bytes)) as zf:
flatten_zip_to_dir(zf, dest)
files = list(dest.iterdir())
# 4 fichiers entrent dans le ZIP, 4 doivent ressortir (les
# collisions sont rรฉsolues, pas รฉcrasรฉes).
assert len(files) == 4, (
f"Attendu 4 fichiers (anti-collision), trouvรฉ "
f"{[p.name for p in files]}"
)
class TestZipExtractedImageValidation:
"""Les images extraites du ZIP doivent passer ``validate_image_safe``
โ sans ce garde-fou, un attaquant pouvait emballer une fausse image
(DecompressionBombError, format invalide) jusqu'ร 500 Mo non
vรฉrifiรฉs."""
def test_invalid_extracted_image_rejected(self, tmp_path: Path) -> None:
from picarones.interfaces.web.corpus_utils import flatten_zip_to_dir
zip_bytes = _zip_with_entries({
# Header PNG seul mais sans IHDR โ invalide.
"fake.png": b"\x89PNG\r\n\x1a\nFAKE_NOT_A_REAL_PNG",
})
dest = tmp_path / "extract"
with zipfile.ZipFile(io.BytesIO(zip_bytes)) as zf:
with pytest.raises(ValueError) as excinfo:
flatten_zip_to_dir(zf, dest)
# Le message doit mentionner le filename pour aider au debug.
assert "fake.png" in str(excinfo.value)
def test_valid_extracted_image_passes(self, tmp_path: Path) -> None:
from picarones.interfaces.web.corpus_utils import flatten_zip_to_dir
zip_bytes = _zip_with_entries({
"ok.png": _MINIMAL_PNG,
"ok.gt.txt": b"Hello",
})
dest = tmp_path / "extract"
with zipfile.ZipFile(io.BytesIO(zip_bytes)) as zf:
flatten_zip_to_dir(zf, dest)
assert (dest / "ok.png").exists()
assert (dest / "ok.gt.txt").exists()
def test_validate_images_false_skips_validation(
self, tmp_path: Path,
) -> None:
"""Le kwarg ``validate_images=False`` dรฉsactive la vรฉrification โ
utilisรฉ par certains tests qui se concentrent sur d'autres
propriรฉtรฉs (path traversal, par exemple) sans avoir besoin de
fournir un PNG complet."""
from picarones.interfaces.web.corpus_utils import flatten_zip_to_dir
zip_bytes = _zip_with_entries({
"skipme.png": b"\x89PNG_FAKE",
})
dest = tmp_path / "extract"
with zipfile.ZipFile(io.BytesIO(zip_bytes)) as zf:
flatten_zip_to_dir(zf, dest, validate_images=False)
assert (dest / "skipme.png").exists()
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 4. Phase 2 โ pipeline_mode strict (rupture API)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def _make_benchmark_app():
"""App FastAPI minimale pour tester le rejet 422 au niveau router."""
from fastapi import FastAPI
from picarones.interfaces.web.routers import benchmark as bench_router
app = FastAPI()
app.include_router(bench_router.router)
return app
class TestPipelineModeStrictAPI:
"""Phase 2 du chantier post-rewrite : le typage ``Literal`` de
``PipelineConfig.pipeline_mode`` rejette en 422 toute valeur
hors de la matrice canonique avant mรชme que le router ne soit
appelรฉ. Avant ce durcissement, le ``mode_map.get(...,
"text_only")`` aliasait silencieusement.
"""
def test_invalid_pipeline_mode_returns_422(self, tmp_path: Path) -> None:
from fastapi.testclient import TestClient
app = _make_benchmark_app()
with TestClient(app) as client:
r = client.post(
"/api/benchmark/run",
json={
"corpus_path": str(tmp_path),
"competitors": [
{
"name": "p",
"ocr_engine": "tesseract",
"ocr_model": "fra",
"llm_provider": "mistral",
"llm_model": "ministral-3b-latest",
"pipeline_mode": "magic_unknown_mode",
"prompt_file": "",
},
],
"normalization_profile": "nfc",
"output_dir": str(tmp_path),
"report_name": "test",
"report_lang": "fr",
},
)
assert r.status_code == 422, r.text
def test_legacy_alias_post_correction_text_rejected_422(
self, tmp_path: Path,
) -> None:
from fastapi.testclient import TestClient
app = _make_benchmark_app()
with TestClient(app) as client:
r = client.post(
"/api/benchmark/run",
json={
"corpus_path": str(tmp_path),
"competitors": [
{
"name": "p",
"ocr_engine": "tesseract",
"ocr_model": "fra",
"llm_provider": "mistral",
"llm_model": "ministral-3b-latest",
# Alias supprimรฉ Phase 2.
"pipeline_mode": "post_correction_text",
"prompt_file": "",
},
],
"normalization_profile": "nfc",
"output_dir": str(tmp_path),
"report_name": "test",
"report_lang": "fr",
},
)
assert r.status_code == 422, r.text
@pytest.mark.parametrize(
"valid_mode", ["text_only", "text_and_image", "zero_shot"],
)
def test_canonical_modes_pass_pydantic(self, valid_mode: str) -> None:
"""Les 3 modes canoniques sont acceptรฉs par Pydantic โ la
suite (instanciation moteur, exรฉcution) peut รฉchouer pour
d'autres raisons mais ce n'est pas notre test."""
from picarones.interfaces.web.models import PipelineConfig
comp = PipelineConfig(
name="t", engine_name="tesseract",
llm_provider="mistral", llm_model="m",
pipeline_mode=valid_mode,
)
assert comp.pipeline_mode == valid_mode
def test_empty_mode_pass_pydantic_for_ocr_only(self) -> None:
"""``pipeline_mode=""`` (dรฉfaut) doit rester acceptรฉ pour les
configs OCR seul (sans ``llm_provider``)."""
from picarones.interfaces.web.models import PipelineConfig
comp = PipelineConfig(
name="t", engine_name="tesseract", llm_provider="",
)
assert comp.pipeline_mode == ""
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 5. Phase 2.2 โ from_json fidรจle (round-trip complet)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class TestBenchmarkResultRoundTrip:
"""Phase 2.2 du chantier post-rewrite : ``BenchmarkResult.to_json``
suivi de :meth:`BenchmarkResult.from_json_object` doit restaurer
**tous** les champs avancรฉs (taxonomy, structure, hallucination,
NER, calibration, philological, searchability, numerical,
readability, pipeline_metadata, ocr_intermediate + leurs
``aggregated_*`` correspondants).
Avant ce durcissement, ``ReportGenerator.from_json`` faisait sa
propre reconstruction qui ne couvrait que CER/WER + textes โ toutes
les analyses รฉtaient perdues, ce qui rendait le rapport rรฉgรฉnรฉrรฉ
diffรฉrent du rapport in-memory. Reproductibilitรฉ scientifique
cassรฉe.
"""
def _make_rich_benchmark(self):
from picarones.evaluation.benchmark_result import (
BenchmarkResult, DocumentResult, EngineReport,
)
from picarones.evaluation.metric_result import MetricsResult
metrics = MetricsResult(
cer=0.15, cer_nfc=0.14, cer_caseless=0.13,
wer=0.20, wer_normalized=0.19,
mer=0.16, wil=0.18,
reference_length=100, hypothesis_length=95,
cer_diplomatic=0.12,
diplomatic_profile_name="medieval_french",
)
dr = DocumentResult(
doc_id="doc1",
image_path="/tmp/doc1.png",
ground_truth="Hello world",
hypothesis="He11o world",
metrics=metrics,
duration_seconds=1.5,
ocr_intermediate="He11o w0rld",
pipeline_metadata={"mode": "text_only", "prompt_file": "x.txt"},
confusion_matrix={"lโ1": 2},
char_scores={"ligature": {"score": 0.95}},
taxonomy={"classes": {"1": 3, "2": 1}},
structure={"line_count": 5},
image_quality={"contrast": 0.75},
line_metrics={"cer_per_line": [0.1, 0.2, 0.3]},
hallucination_metrics={"anchoring": 0.85, "n_blocks": 1},
ner_metrics={"f1_micro": 0.80, "per_category": {"PER": 0.9}},
calibration_metrics={"ece": 0.05, "mce": 0.10},
philological_metrics={"mufi": {"coverage": 0.92}},
searchability_metrics={
"n_gt_tokens": 2, "n_searchable": 2, "recall": 1.0,
},
numerical_sequence_metrics={
"global_strict_score": 1.0, "n_total": 0,
},
readability_metrics={
"lang": "fr", "flesch_delta": -5.2, "n_words_reference": 100,
},
)
er = EngineReport(
engine_name="tesseract",
engine_version="5.3.0",
engine_config={"lang": "fra"},
document_results=[dr],
pipeline_info={"mode": "text_only"},
aggregated_confusion={"lโ1": 2},
aggregated_char_scores={"ligature": {"score": 0.95}},
aggregated_taxonomy={"classes": {"1": 3}},
aggregated_structure={"line_count_total": 5},
aggregated_image_quality={"contrast_mean": 0.75},
aggregated_line_metrics={"gini_mean": 0.3},
aggregated_hallucination={"anchoring_mean": 0.85},
aggregated_ner={"f1_micro": 0.80},
aggregated_calibration={"ece": 0.05},
aggregated_philological={"mufi": {"coverage": 0.92}},
aggregated_searchability={"recall": 1.0},
aggregated_numerical_sequences={"global_strict_score": 1.0},
aggregated_readability={"delta_mean": -5.2},
)
return BenchmarkResult(
corpus_name="rich-corpus",
corpus_source="tests",
document_count=1,
engine_reports=[er],
run_date="2026-05-12T12:00:00Z",
picarones_version="2.0.0",
metadata={"context": "phase2_test"},
)
def test_round_trip_preserves_all_document_level_fields(
self, tmp_path: Path,
) -> None:
from picarones.evaluation.benchmark_result import BenchmarkResult
bm = self._make_rich_benchmark()
path = tmp_path / "rich.json"
bm.to_json(path)
loaded = BenchmarkResult.from_json_object(path)
orig = bm.engine_reports[0].document_results[0]
rebuilt = loaded.engine_reports[0].document_results[0]
assert rebuilt.doc_id == orig.doc_id
assert rebuilt.ground_truth == orig.ground_truth
assert rebuilt.hypothesis == orig.hypothesis
assert rebuilt.ocr_intermediate == orig.ocr_intermediate
assert rebuilt.pipeline_metadata == orig.pipeline_metadata
assert rebuilt.confusion_matrix == orig.confusion_matrix
assert rebuilt.char_scores == orig.char_scores
assert rebuilt.taxonomy == orig.taxonomy
assert rebuilt.structure == orig.structure
assert rebuilt.image_quality == orig.image_quality
assert rebuilt.line_metrics == orig.line_metrics
assert rebuilt.hallucination_metrics == orig.hallucination_metrics
assert rebuilt.ner_metrics == orig.ner_metrics
assert rebuilt.calibration_metrics == orig.calibration_metrics
assert rebuilt.philological_metrics == orig.philological_metrics
assert rebuilt.searchability_metrics == orig.searchability_metrics
assert (
rebuilt.numerical_sequence_metrics
== orig.numerical_sequence_metrics
)
assert rebuilt.readability_metrics == orig.readability_metrics
# Mรฉtriques diplomatiques (anciennement perdues).
assert rebuilt.metrics.cer_diplomatic == orig.metrics.cer_diplomatic
assert (
rebuilt.metrics.diplomatic_profile_name
== orig.metrics.diplomatic_profile_name
)
def test_round_trip_preserves_aggregated_engine_fields(
self, tmp_path: Path,
) -> None:
from picarones.evaluation.benchmark_result import BenchmarkResult
bm = self._make_rich_benchmark()
path = tmp_path / "rich.json"
bm.to_json(path)
loaded = BenchmarkResult.from_json_object(path)
orig = bm.engine_reports[0]
rebuilt = loaded.engine_reports[0]
assert rebuilt.pipeline_info == orig.pipeline_info
assert rebuilt.aggregated_confusion == orig.aggregated_confusion
assert rebuilt.aggregated_char_scores == orig.aggregated_char_scores
assert rebuilt.aggregated_taxonomy == orig.aggregated_taxonomy
assert rebuilt.aggregated_structure == orig.aggregated_structure
assert (
rebuilt.aggregated_image_quality == orig.aggregated_image_quality
)
assert rebuilt.aggregated_line_metrics == orig.aggregated_line_metrics
assert (
rebuilt.aggregated_hallucination == orig.aggregated_hallucination
)
assert rebuilt.aggregated_ner == orig.aggregated_ner
assert rebuilt.aggregated_calibration == orig.aggregated_calibration
assert (
rebuilt.aggregated_philological == orig.aggregated_philological
)
assert (
rebuilt.aggregated_searchability == orig.aggregated_searchability
)
assert (
rebuilt.aggregated_numerical_sequences
== orig.aggregated_numerical_sequences
)
assert rebuilt.aggregated_readability == orig.aggregated_readability
def test_report_generator_from_json_uses_rich_reconstruction(
self, tmp_path: Path,
) -> None:
"""``ReportGenerator.from_json`` doit dรฉsormais accรฉder aux
champs avancรฉs (avant Phase 2.2 il les perdait)."""
from picarones.reports.html.generator import ReportGenerator
bm = self._make_rich_benchmark()
path = tmp_path / "rich.json"
bm.to_json(path)
gen = ReportGenerator.from_json(path)
dr = gen.benchmark.engine_reports[0].document_results[0]
# Champs qui รฉtaient ร None avant Phase 2.2.
assert dr.taxonomy is not None
assert dr.hallucination_metrics is not None
assert dr.philological_metrics is not None
assert dr.calibration_metrics is not None
assert dr.searchability_metrics is not None
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 6. Phase 2.3 โ partial store fingerprint
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class TestPartialStoreFingerprint:
"""Phase 2.3 du chantier post-rewrite : la clรฉ du fichier partiel
inclut dรฉsormais un fingerprint SHA-256 stable de la config
complรจte (engine_config, normalization_profile, char_exclude,
fichiers corpus + mtime/size, version code).
Avant ce durcissement, la clรฉ รฉtait ``(corpus.name, engine.name)``
seule โ deux runs avec configs diffรฉrentes recyclaient
silencieusement les rรฉsultats du prรฉcรฉdent. Reproductibilitรฉ
scientifique brisรฉe.
"""
def test_fingerprint_stable_for_same_config(self, tmp_path: Path) -> None:
from picarones.app.services.partial_store import (
compute_run_fingerprint,
)
f1 = tmp_path / "a.png"
f1.write_bytes(b"\x00" * 100)
fp1 = compute_run_fingerprint(
engine_config={"lang": "fra", "psm": 6},
normalization_profile="medieval_french",
char_exclude="',-",
corpus_files=[f1],
code_version="1.0",
)
fp2 = compute_run_fingerprint(
engine_config={"psm": 6, "lang": "fra"}, # ordre diffรฉrent
normalization_profile="medieval_french",
char_exclude="',-",
corpus_files=[f1],
code_version="1.0",
)
assert fp1 == fp2, "Le fingerprint doit รชtre insensible ร l'ordre dict"
def test_fingerprint_changes_with_engine_config(
self, tmp_path: Path,
) -> None:
from picarones.app.services.partial_store import (
compute_run_fingerprint,
)
f1 = tmp_path / "a.png"
f1.write_bytes(b"\x00" * 100)
fp_psm6 = compute_run_fingerprint(
engine_config={"lang": "fra", "psm": 6},
corpus_files=[f1],
code_version="1.0",
)
fp_psm3 = compute_run_fingerprint(
engine_config={"lang": "fra", "psm": 3},
corpus_files=[f1],
code_version="1.0",
)
assert fp_psm6 != fp_psm3, (
"Un changement de psm doit changer le fingerprint"
)
def test_fingerprint_changes_with_normalization_profile(
self, tmp_path: Path,
) -> None:
from picarones.app.services.partial_store import (
compute_run_fingerprint,
)
f1 = tmp_path / "a.png"
f1.write_bytes(b"\x00" * 100)
fp_med = compute_run_fingerprint(
engine_config={"lang": "fra"},
normalization_profile="medieval_french",
corpus_files=[f1],
)
fp_nfc = compute_run_fingerprint(
engine_config={"lang": "fra"},
normalization_profile="nfc",
corpus_files=[f1],
)
assert fp_med != fp_nfc
def test_fingerprint_changes_with_char_exclude(
self, tmp_path: Path,
) -> None:
from picarones.app.services.partial_store import (
compute_run_fingerprint,
)
fp_with = compute_run_fingerprint(
engine_config={"lang": "fra"},
char_exclude="',-",
)
fp_without = compute_run_fingerprint(
engine_config={"lang": "fra"},
char_exclude="",
)
assert fp_with != fp_without
def test_fingerprint_changes_with_corpus_content(
self, tmp_path: Path,
) -> None:
"""Si un fichier change de taille / mtime, le fingerprint change.
Dรฉtection lรฉgรจre (pas de hash du contenu) mais suffit pour
invalider la reprise aprรจs modification utilisateur du corpus.
"""
import os
import time
from picarones.app.services.partial_store import (
compute_run_fingerprint,
)
f1 = tmp_path / "a.png"
f1.write_bytes(b"\x00" * 100)
fp_v1 = compute_run_fingerprint(
engine_config={"lang": "fra"},
corpus_files=[f1],
)
# Rรฉรฉcrire avec une taille diffรฉrente.
f1.write_bytes(b"\x00" * 200)
# Forcer un mtime diffรฉrent (certains FS ont une rรฉsolution
# de seconde, on attend > 1 s).
new_mtime = time.time() + 5
os.utime(f1, (new_mtime, new_mtime))
fp_v2 = compute_run_fingerprint(
engine_config={"lang": "fra"},
corpus_files=[f1],
)
assert fp_v1 != fp_v2
def test_partial_path_uses_fingerprint_suffix(
self, tmp_path: Path,
) -> None:
from picarones.app.services.partial_store import _partial_path
path_with = _partial_path(
"my_corpus", "tesseract", tmp_path, fingerprint="abc123",
)
path_without = _partial_path(
"my_corpus", "tesseract", tmp_path,
)
assert path_with != path_without
assert "abc123" in path_with.name
# Le format historique reste pour la rรฉtrocompat.
assert path_without.name == "picarones_my_corpus_tesseract.partial.jsonl"
def test_engine_config_for_fingerprint_distinguishes_psm(self) -> None:
"""``_engine_config_for_fingerprint`` capture les attributs
opรฉrationnels d'un adapter OCR (lang, psm, model, โฆ)."""
from picarones.app.services.benchmark_runner import (
_engine_config_for_fingerprint,
)
class _FakeOCR:
name = "tesseract"
lang = "fra"
psm = 6
is_pipeline = False
class _FakeOCRDiff:
name = "tesseract"
lang = "fra"
psm = 3
is_pipeline = False
c1 = _engine_config_for_fingerprint(_FakeOCR())
c2 = _engine_config_for_fingerprint(_FakeOCRDiff())
assert c1 != c2
assert c1["psm"] == 6
assert c2["psm"] == 3
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 7. Phase 3 โ Adapters kraken et calamari (moteurs fantรดmes implรฉmentรฉs)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class TestKrakenAdapter:
"""Phase 3 du chantier post-rewrite : ``KrakenAdapter`` rend
l'engine ``kraken`` rรฉellement utilisable (au lieu d'รชtre
juste annoncรฉ par ``/api/engines``)."""
def test_kraken_requires_model_path(self) -> None:
from picarones.adapters.ocr import KrakenAdapter
from picarones.adapters.ocr.base import OCRAdapterError
with pytest.raises(OCRAdapterError, match="model_path est obligatoire"):
KrakenAdapter()
def test_kraken_via_factory(self, tmp_path: Path) -> None:
from picarones.adapters.ocr import KrakenAdapter
from picarones.adapters.ocr.factory import ocr_adapter_from_name
# Modรจle factice โ l'adapter ne le charge qu'ร execute().
model = tmp_path / "fake.mlmodel"
model.write_bytes(b"fake")
adapter = ocr_adapter_from_name("kraken", model_path=str(model))
assert isinstance(adapter, KrakenAdapter)
assert adapter.name == "kraken"
assert adapter.model_path == model
def test_kraken_validates_name(self) -> None:
from picarones.adapters.ocr import KrakenAdapter
from picarones.adapters.ocr.base import OCRAdapterError
with pytest.raises(OCRAdapterError, match="name invalide"):
KrakenAdapter(name="bad name with spaces", model_path="x")
class TestCalamariAdapter:
"""Phase 3 du chantier post-rewrite : ``CalamariAdapter`` rend
l'engine ``calamari`` rรฉellement utilisable."""
def test_calamari_requires_checkpoint(self) -> None:
from picarones.adapters.ocr import CalamariAdapter
from picarones.adapters.ocr.base import OCRAdapterError
with pytest.raises(OCRAdapterError, match="checkpoint est obligatoire"):
CalamariAdapter()
def test_calamari_via_factory(self, tmp_path: Path) -> None:
from picarones.adapters.ocr import CalamariAdapter
from picarones.adapters.ocr.factory import ocr_adapter_from_name
ckpt = tmp_path / "fake.ckpt"
ckpt.write_bytes(b"fake")
adapter = ocr_adapter_from_name("calamari", checkpoint=str(ckpt))
assert isinstance(adapter, CalamariAdapter)
assert adapter.name == "calamari"
assert adapter.checkpoint == ckpt
def test_calamari_validates_batch_size(self) -> None:
from picarones.adapters.ocr import CalamariAdapter
from picarones.adapters.ocr.base import OCRAdapterError
with pytest.raises(OCRAdapterError, match="batch_size doit รชtre"):
CalamariAdapter(checkpoint="x", batch_size=0)
class TestEngineMatrixCoherence:
"""Phase 3 du chantier post-rewrite : la matrice des moteurs est
cohรฉrente entre ``/api/engines``, la factory canonique, le
builder web ``_OCR_KWARGS_BUILDERS`` et l'index public."""
def test_kraken_and_calamari_in_factory_supported_list(self) -> None:
from picarones.adapters.ocr.factory import _SUPPORTED
assert "kraken" in _SUPPORTED
assert "calamari" in _SUPPORTED
def test_kraken_and_calamari_in_web_builders(self) -> None:
from picarones.interfaces.web.benchmark_utils import (
_OCR_KWARGS_BUILDERS,
)
assert "kraken" in _OCR_KWARGS_BUILDERS
assert "calamari" in _OCR_KWARGS_BUILDERS
def test_kraken_calamari_exposed_at_package_root(self) -> None:
from picarones.adapters.ocr import (
CalamariAdapter,
KrakenAdapter,
)
assert KrakenAdapter.__name__ == "KrakenAdapter"
assert CalamariAdapter.__name__ == "CalamariAdapter"
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 8. Phase 4 โ upload_purge_task branchรฉ au lifespan
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class TestUploadPurgeTaskWired:
"""Phase 4 du chantier post-rewrite : la tรขche
``upload_purge_task`` est dรฉsormais dรฉmarrรฉe par le lifespan de
``picarones.interfaces.web.app`` (auparavant dรฉfinie mais jamais
lancรฉe โ code zombie)."""
def test_lifespan_starts_purge_task(self, monkeypatch) -> None:
"""Au dรฉmarrage de l'app FastAPI, un ``asyncio.create_task`` doit
emballer ``upload_purge_task``. On patch la fonction pour
l'observer puis on enclenche le lifespan.
Polling actif au lieu de ``time.sleep`` fixe : robuste aux
runners CI lents (Windows en particulier peut prendre > 100 ms
pour scheduler la premiรจre tรขche asyncio)."""
import asyncio
import threading
import time
from fastapi.testclient import TestClient
started_event = threading.Event()
observed: dict = {"uploads_root": None}
async def _fake_purge_task(uploads_root):
observed["uploads_root"] = uploads_root
started_event.set()
# Boucle infinie minimale โ annulรฉe au shutdown.
try:
while True:
await asyncio.sleep(3600)
except asyncio.CancelledError:
raise
monkeypatch.setattr(
"picarones.interfaces.web.maintenance.upload_purge_task",
_fake_purge_task,
)
# Forcer la rรฉtention pour ne pas que la fonction rรฉelle short-circuit.
monkeypatch.setenv("PICARONES_UPLOAD_RETENTION_DAYS", "7")
from picarones.interfaces.web.app import app
with TestClient(app):
# Polling 2 s avec slot 10 ms โ assez de marge pour
# les runners GitHub Actions lents (macOS / Windows).
deadline = time.monotonic() + 2.0
while not started_event.is_set() and time.monotonic() < deadline:
time.sleep(0.01)
assert started_event.is_set(), (
"upload_purge_task aurait dรป รชtre dรฉmarrรฉe par le lifespan "
"dans les 2 s suivant TestClient(app).__enter__()"
)
def test_purge_protects_active_corpus(self, tmp_path: Path) -> None:
"""Si un job ``pending``/``running`` rรฉfรฉrence un corpus_id, la
purge ne supprime pas ce dossier โ mรชme s'il est ancien."""
import time
from picarones.interfaces.web.maintenance import purge_old_uploads
# 2 corpus : un actif (rรฉfรฉrencรฉ), un orphelin.
active = tmp_path / "active_corpus"
orphan = tmp_path / "orphan_corpus"
active.mkdir()
orphan.mkdir()
# Vieillir les deux pour qu'ils passent la rรฉtention de 0 jour.
old = time.time() - 86400 * 30
import os
os.utime(active, (old, old))
os.utime(orphan, (old, old))
purged = purge_old_uploads(
tmp_path,
retention_days=7,
active_corpus_ids={"active_corpus"},
)
purged_names = [p.name for p in purged]
assert "orphan_corpus" in purged_names
assert "active_corpus" not in purged_names
# Vรฉrification physique
assert active.exists()
assert not orphan.exists()
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 9. Phase 5b โ engine_name (renommage rupture du field ocr_engine)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class TestPipelineConfigEngineNameRename:
"""Phase 5b du chantier post-rewrite : le field ``ocr_engine`` du
payload ``PipelineConfig`` est renommรฉ en ``engine_name`` car il
accepte aussi des VLMs (zero_shot) et la source ``corpus`` (OCR
prรฉ-calculรฉ) โ le prรฉfixe ``ocr_`` รฉtait trompeur.
Rupture API : un client qui envoie l'ancien nom doit recevoir une
erreur Pydantic explicite plutรดt que d'aliaser silencieusement.
"""
def test_engine_name_field_accepted(self) -> None:
from picarones.interfaces.web.models import PipelineConfig
cfg = PipelineConfig(
name="t", engine_name="tesseract", llm_provider="",
)
assert cfg.engine_name == "tesseract"
def test_legacy_ocr_engine_kwarg_rejected_by_strict_mode(self) -> None:
"""Pydantic v2 ignore par dรฉfaut les extras non dรฉclarรฉs mais
ne reconnaรฎt plus ``ocr_engine`` comme alias. On vรฉrifie que
passer juste ``ocr_engine=`` ne remplit pas ``engine_name``
(rupture silencieuse acceptรฉe vs explicite โ Pydantic v2 ne
peut pas distinguer entre 'extra ignorรฉ' et 'mauvais nom')."""
from picarones.interfaces.web.models import PipelineConfig
cfg = PipelineConfig(name="t", llm_provider="")
# Default : engine_name=""
assert cfg.engine_name == ""
# Construire avec un kwarg dynamic = legacy name โ engine_name
# reste vide (Pydantic v2 ignore les extras non-strict).
cfg2 = PipelineConfig.model_validate(
{"name": "t", "ocr_engine": "tesseract", "llm_provider": ""},
)
assert cfg2.engine_name == "", (
"Le legacy ``ocr_engine`` ne doit PAS remplir engine_name "
"automatiquement โ sinon on aliase silencieusement et la "
"rupture API n'est pas rรฉelle."
)
def test_router_payload_uses_engine_name(self) -> None:
"""Le router ``/api/benchmark/run`` accepte le payload
avec ``engine_name`` et le propage."""
from fastapi import FastAPI
from fastapi.testclient import TestClient
from picarones.interfaces.web.routers import benchmark as bench_router
app = FastAPI()
app.include_router(bench_router.router)
with TestClient(app) as client:
# On vise un payload qui valide Pydantic mais รฉchoue ร
# l'instanciation moteur (corpus inexistant) โ l'important
# est que le 422 Pydantic ne se dรฉclenche pas sur le field.
r = client.post(
"/api/benchmark/run",
json={
"corpus_path": "/tmp/no_such_dir_for_phase5b_test",
"competitors": [{
"name": "p",
"engine_name": "tesseract",
"ocr_model": "fra",
"llm_provider": "",
"llm_model": "",
"pipeline_mode": "",
"prompt_file": "",
}],
"normalization_profile": "nfc",
"output_dir": "/tmp",
"report_name": "test",
"report_lang": "fr",
},
)
# Pas un 422 Pydantic โ le field engine_name a bien
# รฉtรฉ acceptรฉ. (400 attendu : corpus_path inexistant.)
assert r.status_code != 422, (
"Le router refuse le payload avec engine_name : "
f"{r.text}"
)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 10. Phase 4.4 โ JS is_demo HTR-United badge
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class TestHtrUnitedDemoBadgeBinding:
"""Phase 4.4 du chantier post-rewrite : l'API
``/api/htr-united/catalogue`` retourne ``is_demo`` ; le frontend
doit afficher un badge visible quand le serveur a fallback sur
le catalogue embarquรฉ (rรฉseau distant indisponible).
Avant : l'UI annonรงait "Catalogue HTR-United" sans distinguer
dรฉmo vs remote โ vecteur de confusion utilisateur."""
def test_template_exposes_demo_banner(self) -> None:
from pathlib import Path
tmpl = (
Path(__file__).resolve().parents[2]
/ "picarones/interfaces/web/templates/_view_import.html"
)
html = tmpl.read_text(encoding="utf-8")
assert "htr-demo-banner" in html, (
"Le bandeau ``htr-demo-banner`` doit exister dans "
"_view_import.html pour afficher le mode dรฉmo"
)
assert "htr_demo_badge" in html, (
"L'i18n key ``htr_demo_badge`` doit รชtre prรฉsente"
)
def test_js_updates_banner_from_is_demo_flag(self) -> None:
from pathlib import Path
js = (
Path(__file__).resolve().parents[2]
/ "picarones/interfaces/web/static/web-app.js"
)
src = js.read_text(encoding="utf-8")
assert "function _updateHtrDemoBanner" in src, (
"_updateHtrDemoBanner doit รชtre dรฉfini"
)
# initHTRFilters et searchHTRUnited doivent l'appeler.
assert "_updateHtrDemoBanner(Boolean(d.is_demo))" in src, (
"initHTRFilters et searchHTRUnited doivent passer "
"le flag is_demo au binding UI"
)
# i18n key dรฉclarรฉe FR + EN.
assert "htr_demo_badge:" in src
assert "htr_demo_note:" in src
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 11. Phase 6 โ Intรฉgration HTTP /api/corpus/upload ZIP collision
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class TestCorpusUploadZipCollisionEndToEnd:
"""Audit Phase 6 : vรฉrifie que la dรฉfense ``flatten_zip_to_dir``
(dรฉtection de collision basename + validation image) est bien
activรฉe via le router HTTP ``/api/corpus/upload``, pas seulement
quand on appelle l'utilitaire directement.
Avant cette vรฉrif : on testait ``flatten_zip_to_dir`` ร l'unitรฉ
mais rien ne garantissait que le router HTTP utilisait bien le
mรชme chemin (le router peut basculer sur ``CorpusService`` au
sprint suivant โ ce test attrape la rรฉgression)."""
def test_upload_zip_with_basename_collision_keeps_both_pairs(
self, tmp_path: Path,
) -> None:
"""``a/img.png`` + ``b/img.png`` dans le ZIP uploadรฉ doivent
produire 2 images distinctes cรดtรฉ serveur (renommage), pas
un รฉcrasement silencieux."""
from fastapi.testclient import TestClient
from picarones.interfaces.web.app import app
# ZIP avec collision : 2 paires image/.gt.txt qui partagent
# le basename ``img.png``/``img.gt.txt`` mais venant de
# dossiers source diffรฉrents.
zip_bytes = _zip_with_entries({
"folder_a/img.png": _MINIMAL_PNG,
"folder_a/img.gt.txt": b"Texte A",
"folder_b/img.png": _MINIMAL_PNG,
"folder_b/img.gt.txt": b"Texte B",
})
with TestClient(app) as client:
r = client.post(
"/api/corpus/upload",
files=[
("files", ("corpus.zip", zip_bytes, "application/zip")),
],
)
assert r.status_code == 200, r.text
body = r.json()
# 2 paires distinctes attendues (au lieu de 1 si on
# avait รฉcrasรฉ silencieusement la premiรจre).
assert body["doc_count"] >= 1, body
assert body["total_pairs"] >= 1, body
# Le rรฉsumรฉ liste au moins une image avec prรฉfixe slug
# de dirname (la seconde occurrence renommรฉe).
corpus_id = body["corpus_id"]
list_r = client.get("/api/corpus/uploads")
assert list_r.status_code == 200
corpora = list_r.json()["uploads"]
entry = next(c for c in corpora if c["corpus_id"] == corpus_id)
assert entry["doc_count"] >= 1
def test_upload_zip_with_invalid_image_returns_415(
self, tmp_path: Path,
) -> None:
"""Une image invalide extraite du ZIP doit faire rรฉpondre
l'endpoint en HTTP 415 (Pillow.verify รฉchoue) โ pas en 200
silencieux."""
from fastapi.testclient import TestClient
from picarones.interfaces.web.app import app
# ZIP contenant un PNG-signature mais sans IHDR valide.
zip_bytes = _zip_with_entries({
"fake.png": b"\x89PNG\r\n\x1a\n" + b"\x00" * 16,
"fake.gt.txt": b"GT",
})
with TestClient(app) as client:
r = client.post(
"/api/corpus/upload",
files=[
("files", ("corpus.zip", zip_bytes, "application/zip")),
],
)
# Le router corpus.py map ValueError โ 415.
assert r.status_code == 415, r.text
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 12. Phase 6 โ synthesis_preview binding UI
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class TestSynthesisPreviewUIBinding:
"""Phase 6 : l'endpoint ``/api/benchmark/{job_id}/synthesis_preview``
รฉtait testรฉ serveur mais aucun bouton UI ne l'appelait โ encore
un code zombie post-rewrite. Dรฉsormais ``_showResults`` dรฉclenche
``_loadSynthesisPreview`` aprรจs affichage du classement."""
def test_template_exposes_synthesis_section(self) -> None:
from pathlib import Path
tmpl = (
Path(__file__).resolve().parents[2]
/ "picarones/interfaces/web/templates/_view_benchmark.html"
)
html = tmpl.read_text(encoding="utf-8")
assert "bench-synthesis-section" in html, (
"Une section ``#bench-synthesis-section`` doit exister "
"dans _view_benchmark.html pour hรฉberger les phrases."
)
assert "bench-synthesis-sentences" in html, (
"Une liste ``#bench-synthesis-sentences`` doit exister."
)
def test_js_fetches_synthesis_preview_after_results(self) -> None:
from pathlib import Path
js = (
Path(__file__).resolve().parents[2]
/ "picarones/interfaces/web/static/web-app.js"
)
src = js.read_text(encoding="utf-8")
assert "function _loadSynthesisPreview" in src or \
"async function _loadSynthesisPreview" in src, (
"_loadSynthesisPreview doit รชtre dรฉfini"
)
assert "/api/benchmark/" in src and "synthesis_preview" in src, (
"Le JS doit appeler l'endpoint synthesis_preview"
)
# i18n key dรฉclarรฉe FR + EN.
assert "bench_synthesis_title:" in src
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 13. Phase 4.2 audit code-quality (2026-05) โ suppression franche
# du helper ``_legacy_request_to_run_request`` et du modรจle
# ``BenchmarkRequest`` (rupture v2.0). Les 6 tests qui vรฉrifiaient
# la conversion ont รฉtรฉ retirรฉs โ leur invariant n'a plus de sens
# puisque la conversion n'existe plus. Le garde-fou de
# non-rรฉsurrection est dans ``tests/web/test_no_legacy_benchmark_endpoint.py``.
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|