Spaces:
Running
Running
Upload 13 files
Browse files- INSTALLATION-v4.23.0.md +68 -0
- PATCH-MANIFEST-v4.23.0.json +38 -0
- VALIDATION-v4.23.0.json +28 -0
- config/surface-manifest-v1.json +44 -8
- src/candidates.py +192 -0
- src/label_transfer.py +181 -0
- src/multi_surface.py +8 -1
- src/production_ui.py +181 -35
- src/surface_manifest.py +58 -5
- src/unified_pipeline.py +5 -1
- src/vc3d_bridge.py +161 -20
- tests/test_production_v422.py +70 -10
- tests/test_validation_v423.py +240 -0
INSTALLATION-v4.23.0.md
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# UNIQUE — 4.23.0 : validation indépendante sur PHerc0841 w00, tri géométrique, dossier de ROI
|
| 2 |
+
|
| 3 |
+
Mise à jour pour le Space en **4.22.0**. Aucune dépendance ajoutée ni modifiée.
|
| 4 |
+
|
| 5 |
+
## Ce que la version apporte
|
| 6 |
+
|
| 7 |
+
1. **Annotations publiques de PHerc0841 w00** (`src/label_transfer.py`). Elles sont posées sur la surface rendue à
|
| 8 |
+
2,403 µm (15872 × 18944), alors que le modèle lit la surface à 9,366 µm (4220 × 4760) : deux repères plats différents.
|
| 9 |
+
Le passage se fait par trois maillages publics, sans aucune mise à l'échelle supposée :
|
| 10 |
+
pixel 9,366 µm → même nœud dans le volume 2,403 µm (maillage `…-2.403um-t2.tifxyz`) → projection sur le maillage
|
| 11 |
+
des annotations (`ink/841/w00`) → pixel annoté.
|
| 12 |
+
2. **Deux portes géométriques, tolérance 9,366 µm (un pixel du modèle)**. Le maillage « pont » doit avoir la grille du
|
| 13 |
+
maillage natif et s'en déduire par une transformation affine ; puis 95 % au moins des pixels de la ROI doivent se
|
| 14 |
+
projeter à moins de la tolérance du maillage annoté. Une porte refusée donne un rapport sans métrique, avec le motif.
|
| 15 |
+
3. **Plan de ROI de w00** refait à partir des annotations publiques vues par ce transfert (encre annotée d'abord).
|
| 16 |
+
Le plan 4.22.0 de w00, fondé sur la seule validité du maillage, est remplacé ; les autres plans sont inchangés.
|
| 17 |
+
4. **Tri géométrique** (`src/candidates.py`). Par composante : aire réelle (corrigée de l'étirement du maillage), axes,
|
| 18 |
+
allongement, orientation, score moyen, appui du sens inversé, asymétrie direct/inversé, sensibilité à la profondeur.
|
| 19 |
+
Par ROI : orientation dominante, espacement médian, périodicité des lignes. Les portes de tri sont étalonnées une
|
| 20 |
+
seule fois sur les composantes annotées de w00 (seuil de Youden, mesures d'AUC ≥ 0,70 seulement), puis figées.
|
| 21 |
+
5. **Dossier de ROI** dans le panneau Production : vue 3D rapprochée face à la surface, CT, scores, composantes
|
| 22 |
+
entourées (vert retenu, rouge écarté, ambre non étalonné), écarts aux annotations, tableau des mesures.
|
| 23 |
+
Le champ de transcription est vide par construction : aucun texte, glyphe ou lecture n'est produit.
|
| 24 |
+
6. **Affichage 3D** : fond sombre, maillage éclairé en gris neutre, ROI numérotées, ROI ouverte en bleu, plan de
|
| 25 |
+
situation plat à côté de la vue 3D, vue rapprochée sans miroir (x plat à droite, y plat en bas, comme les images).
|
| 26 |
+
Sous la nappe de scores, les mailles sont retirées pour supprimer le scintillement de deux surfaces confondues.
|
| 27 |
+
7. **Tableau de la boucle** : colonnes réordonnées (métriques d'abord), libellés courts en français, retour à la ligne.
|
| 28 |
+
|
| 29 |
+
## Installation
|
| 30 |
+
|
| 31 |
+
1. Décompresser le ZIP à la racine du Space, en remplaçant les fichiers existants, dans un seul commit.
|
| 32 |
+
2. Recharger la page, vérifier **4.23.0**, puis **Vérifier les sources** : la ligne PHerc0841 doit indiquer
|
| 33 |
+
« pont 3D vérifié » avec son résidu. « PONT 3D REFUSÉ » donne le motif chiffré ; la boucle tourne alors sans annotation.
|
| 34 |
+
3. Lancer la boucle sur PHerc0841 w00 seule, 4 à 8 ROI.
|
| 35 |
+
4. **Étalonner les portes de tri** une fois la boucle terminée (30 composantes « encre » et 30 « sans encre » requises).
|
| 36 |
+
5. **Charger le maillage 3D**, choisir une ROI, **Ouvrir le dossier de la ROI**.
|
| 37 |
+
|
| 38 |
+
```bash
|
| 39 |
+
python -m pytest -q tests src/pipeline_contracts.py -p no:cacheprovider
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
## Ce qui est vérifié, et ce qui ne l'est pas
|
| 43 |
+
|
| 44 |
+
Vérifié localement (Gradio 6.32.0, torch CPU) : **147 tests réussis**, dont 10 nouveaux. Le transfert est testé sur une
|
| 45 |
+
surface d'essai dont les annotations vivent sur une autre grille plate (échelles 3,8 et 4,1, décalage de 30 px) : les
|
| 46 |
+
annotations retombent au pixel près, et les trois cas de refus (maillage annoté décalé de 72 µm, pont d'une autre grille,
|
| 47 |
+
pont non affine) sont refusés. Le seul échec local reste `test_asgi_primary_dashboard_and_downloads_share_authentication`
|
| 48 |
+
(paquet `mouh` absent hors du Space).
|
| 49 |
+
|
| 50 |
+
**Non vérifié : le transfert sur les vrais maillages de w00.** Trois hypothèses seront tranchées par les portes au
|
| 51 |
+
premier clic sur **Vérifier les sources** :
|
| 52 |
+
|
| 53 |
+
- le maillage `-t2` a la même grille (211 × 238) que le maillage 9,366 µm ; les tailles de fichier le suggèrent
|
| 54 |
+
(201 144 et 201 006 octets), rien de plus ;
|
| 55 |
+
- les volumes 9,366 µm et 2,403 µm se correspondent par une transformation affine à 9,366 µm près ;
|
| 56 |
+
- le maillage des annotations (`w00_transformed`) suit la même surface que le maillage public, à 9,366 µm près.
|
| 57 |
+
|
| 58 |
+
Si l'une est fausse, le transfert est refusé et aucune métrique n'est produite ; le motif affiché dira laquelle.
|
| 59 |
+
Les figures 3D n'ont pas été regardées dans un navigateur. Aucun calcul GPU n'a été exécuté.
|
| 60 |
+
|
| 61 |
+
## Limites
|
| 62 |
+
|
| 63 |
+
- La mesure sur w00 porte sur les ROI du plan, pas sur la surface entière, et la zone annotée réunit les masques publics
|
| 64 |
+
de supervision et de validation. Elle est indépendante de l'entraînement d'ink_9um d'après sa fiche, non certifiée.
|
| 65 |
+
- Les portes de tri sont étalonnées sur w00 elle-même : leur réussite y est optimiste. Leur valeur se jugera ailleurs.
|
| 66 |
+
- « Retenu » décrit une forme stable et cohérente avec le maillage, pas de l'encre ni un caractère.
|
| 67 |
+
- La 4.22.0 a montré W8 refusé par la qualification sur toutes les ROI déjà traitées ; la 4.23.0 n'y change rien et
|
| 68 |
+
affiche ce compte dans le résumé. Le motif chiffré est dans `engine_decision.fallback_reasons` de chaque rapport.
|
PATCH-MANIFEST-v4.23.0.json
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"version": "4.23.0",
|
| 3 |
+
"requires": "4.22.0",
|
| 4 |
+
"target": "RDS777/TARGET_SPACE",
|
| 5 |
+
"files_sha256": {
|
| 6 |
+
"config/surface-manifest-v1.json": "23e9f9119af54046da722a58596388ee1e8157e269e6f86ddbb6e62a5548c863",
|
| 7 |
+
"src/multi_surface.py": "f140b062cb9e18c2613a7aa991b7e6afbca5195f7f87a16fff04ed7f6e7a00c5",
|
| 8 |
+
"src/production_ui.py": "715c5f2a7b8c4789b935452523b3bb1b4d0fb783a41dad161f042cead26806fb",
|
| 9 |
+
"src/surface_manifest.py": "8b65a9f12b9b1ba0512795c220b61eaa422688cfcbb4829126c471a7c627ffa3",
|
| 10 |
+
"src/unified_pipeline.py": "6c47e0a1ade8bdeb5ae24630cc3a1bfd831dc61131da29af1bcfa7da6d77122f",
|
| 11 |
+
"src/vc3d_bridge.py": "6497dd9b1040e067f78e7180bc6c72483915167dcb29f2850fedd61e6b0da3be",
|
| 12 |
+
"tests/test_production_v422.py": "a50ba05ad49c393f9c9d02abc1120971176594ac5451b6d5e15441f5c18a9809",
|
| 13 |
+
"INSTALLATION-v4.23.0.md": "21035a923a618e62fd683c3df4f5c330ef7c839a2db53819458979397eb3c5b6",
|
| 14 |
+
"src/candidates.py": "2e98e41e77c882272ad0ad4f2dfdc06db73f50a7ed84b6831ee7a805f04a4593",
|
| 15 |
+
"src/label_transfer.py": "bd14d4627d25b04f85088231237a2360021d2d861b95bb0b9b07798b92cfb068",
|
| 16 |
+
"tests/test_validation_v423.py": "826fd8f72df8b71a7f5206298ff55aefb3a680d1201760c0eb8503ce55d1b9e2",
|
| 17 |
+
"VALIDATION-v4.23.0.json": "88badaa23c561d47fa358068c57ba0069c9845d7ccc1f0f6b6b483fb27b324dc"
|
| 18 |
+
},
|
| 19 |
+
"base_sha256": {
|
| 20 |
+
"config/surface-manifest-v1.json": "108fc62697c4bd2bb456961463b0c72b1475bf15a14d667846e8fab9ca7c39ff",
|
| 21 |
+
"src/multi_surface.py": "3e5304cbfb0d124045a5909b19f0f01933698ce178f15703d26f56fddfe63a7f",
|
| 22 |
+
"src/production_ui.py": "480ed3a6212572eef1917882a1d43094bf19bb4ecde5ad5f15a38460f8e48b7e",
|
| 23 |
+
"src/surface_manifest.py": "dbd5d02dc6d90e97fe71a225798c8144102dca0fd229a13d8194142f1f7a36c4",
|
| 24 |
+
"src/unified_pipeline.py": "7a8bf3c20d1d382242a0225428791ed01aadbfa778048bbd51e10450db66e07e",
|
| 25 |
+
"src/vc3d_bridge.py": "3a50da54ccf9350ff2839357ed97d17536273d66efbb65091d0e8b1404085457",
|
| 26 |
+
"tests/test_production_v422.py": "28859f36dfbaacaed3602db67d3c12010a595871da0409763e789cad72cbde90"
|
| 27 |
+
},
|
| 28 |
+
"new_files": [
|
| 29 |
+
"INSTALLATION-v4.23.0.md",
|
| 30 |
+
"src/candidates.py",
|
| 31 |
+
"src/label_transfer.py",
|
| 32 |
+
"tests/test_validation_v423.py",
|
| 33 |
+
"VALIDATION-v4.23.0.json",
|
| 34 |
+
"PATCH-MANIFEST-v4.23.0.json"
|
| 35 |
+
],
|
| 36 |
+
"ct_data_included": false,
|
| 37 |
+
"model_weights_included": false
|
| 38 |
+
}
|
VALIDATION-v4.23.0.json
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"version": "4.23.0",
|
| 3 |
+
"requires": "4.22.0",
|
| 4 |
+
"scope": "gated 3D label transfer for PHerc0841 w00, label-driven ROI plan, geometric component triage with one-time frozen calibration, ROI dossier, reworked 3D views",
|
| 5 |
+
"local_tests": {
|
| 6 |
+
"gradio": "6.32.0",
|
| 7 |
+
"passed": 147,
|
| 8 |
+
"new_tests": 10,
|
| 9 |
+
"failed": 1,
|
| 10 |
+
"failed_test": "tests/test_unified.py::test_asgi_primary_dashboard_and_downloads_share_authentication",
|
| 11 |
+
"failure_cause": "package mouh absent from the preparation environment; same failure in 4.21.7 and 4.22.0"
|
| 12 |
+
},
|
| 13 |
+
"transfer_tested_on": "synthetic surface with labels on a different flat grid (scales 3.8/4.1, 30 px offset); pixel-exact, three refusal cases refused",
|
| 14 |
+
"real_w00_transfer_executed": false,
|
| 15 |
+
"assumptions_decided_by_gates_on_space": [
|
| 16 |
+
"-t2 mesh shares the 211x238 grid of the 9.366 um mesh",
|
| 17 |
+
"9.366 um and 2.403 um volume frames agree affinely within 9.366 um",
|
| 18 |
+
"label mesh w00_transformed lies within 9.366 um of the public surface"
|
| 19 |
+
],
|
| 20 |
+
"transcription_generated": false,
|
| 21 |
+
"glyph_matching": false,
|
| 22 |
+
"native_cuda_executed_locally": false,
|
| 23 |
+
"browser_rendering_checked": false,
|
| 24 |
+
"legacy_protocol_modified": false,
|
| 25 |
+
"requirements_modified": false,
|
| 26 |
+
"scientific_result_produced": false,
|
| 27 |
+
"submission_ready": false
|
| 28 |
+
}
|
config/surface-manifest-v1.json
CHANGED
|
@@ -11,7 +11,12 @@
|
|
| 11 |
"volume": "9.362um-1.2m-113keV-volume-20250728140407.zarr",
|
| 12 |
"voxel_um": 9.362,
|
| 13 |
"labels": null,
|
| 14 |
-
"origins_yx": [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
"provenance": {
|
| 16 |
"scroll": "PHerc0139",
|
| 17 |
"status": "seen_roll",
|
|
@@ -26,7 +31,11 @@
|
|
| 26 |
"segment": "s3://vesuvius-challenge-open-data/PHerc0139/segments/20260317000000-w035_2026031718",
|
| 27 |
"volume": "9.362um-1.2m-113keV-volume-20250728140407.zarr",
|
| 28 |
"voxel_um": 9.362,
|
| 29 |
-
"labels": {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
"origins_yx": null,
|
| 31 |
"provenance": {
|
| 32 |
"scroll": "PHerc0139",
|
|
@@ -42,7 +51,11 @@
|
|
| 42 |
"segment": "s3://vesuvius-challenge-open-data/PHerc0139/segments/20260302000000-w039_2026030210",
|
| 43 |
"volume": "9.362um-1.2m-113keV-volume-20250728140407.zarr",
|
| 44 |
"voxel_um": 9.362,
|
| 45 |
-
"labels": {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
"origins_yx": null,
|
| 47 |
"provenance": {
|
| 48 |
"scroll": "PHerc0139",
|
|
@@ -58,7 +71,11 @@
|
|
| 58 |
"segment": "s3://vesuvius-challenge-open-data/PHerc0139/segments/20250831000000-w040_2025083102",
|
| 59 |
"volume": "9.362um-1.2m-113keV-volume-20250728140407.zarr",
|
| 60 |
"voxel_um": 9.362,
|
| 61 |
-
"labels": {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
"origins_yx": null,
|
| 63 |
"provenance": {
|
| 64 |
"scroll": "PHerc0139",
|
|
@@ -74,7 +91,11 @@
|
|
| 74 |
"segment": "s3://vesuvius-challenge-open-data/PHerc0139/segments/20260108000000-w041_2026010816",
|
| 75 |
"volume": "9.362um-1.2m-113keV-volume-20250728140407.zarr",
|
| 76 |
"voxel_um": 9.362,
|
| 77 |
-
"labels": {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
"origins_yx": null,
|
| 79 |
"provenance": {
|
| 80 |
"scroll": "PHerc0139",
|
|
@@ -90,7 +111,11 @@
|
|
| 90 |
"segment": "s3://vesuvius-challenge-open-data/PHerc0139/segments/20260115000000-w044_2026011522",
|
| 91 |
"volume": "9.362um-1.2m-113keV-volume-20250728140407.zarr",
|
| 92 |
"voxel_um": 9.362,
|
| 93 |
-
"labels": {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
"origins_yx": null,
|
| 95 |
"provenance": {
|
| 96 |
"scroll": "PHerc0139",
|
|
@@ -102,11 +127,22 @@
|
|
| 102 |
{
|
| 103 |
"case": "pherc0841-w00",
|
| 104 |
"scroll": "PHerc0841",
|
| 105 |
-
"label": "PHerc0841 · w00 · 9,366 µm natif ·
|
| 106 |
"segment": "s3://vesuvius-challenge-open-data/PHerc0841/segments/20260220213127-w00",
|
| 107 |
"volume": "9.366um-1.2m-113keV-volume-20250821151531.zarr",
|
| 108 |
"voxel_um": 9.366,
|
| 109 |
-
"labels":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
"origins_yx": null,
|
| 111 |
"provenance": {
|
| 112 |
"scroll": "PHerc0841",
|
|
|
|
| 11 |
"volume": "9.362um-1.2m-113keV-volume-20250728140407.zarr",
|
| 12 |
"voxel_um": 9.362,
|
| 13 |
"labels": null,
|
| 14 |
+
"origins_yx": [
|
| 15 |
+
[
|
| 16 |
+
2800,
|
| 17 |
+
3800
|
| 18 |
+
]
|
| 19 |
+
],
|
| 20 |
"provenance": {
|
| 21 |
"scroll": "PHerc0139",
|
| 22 |
"status": "seen_roll",
|
|
|
|
| 31 |
"segment": "s3://vesuvius-challenge-open-data/PHerc0139/segments/20260317000000-w035_2026031718",
|
| 32 |
"volume": "9.362um-1.2m-113keV-volume-20250728140407.zarr",
|
| 33 |
"voxel_um": 9.362,
|
| 34 |
+
"labels": {
|
| 35 |
+
"family": "native9-scrollprizeorg-21slices",
|
| 36 |
+
"segment": "w035",
|
| 37 |
+
"plane": 14
|
| 38 |
+
},
|
| 39 |
"origins_yx": null,
|
| 40 |
"provenance": {
|
| 41 |
"scroll": "PHerc0139",
|
|
|
|
| 51 |
"segment": "s3://vesuvius-challenge-open-data/PHerc0139/segments/20260302000000-w039_2026030210",
|
| 52 |
"volume": "9.362um-1.2m-113keV-volume-20250728140407.zarr",
|
| 53 |
"voxel_um": 9.362,
|
| 54 |
+
"labels": {
|
| 55 |
+
"family": "native9-scrollprizeorg-21slices",
|
| 56 |
+
"segment": "w039",
|
| 57 |
+
"plane": 14
|
| 58 |
+
},
|
| 59 |
"origins_yx": null,
|
| 60 |
"provenance": {
|
| 61 |
"scroll": "PHerc0139",
|
|
|
|
| 71 |
"segment": "s3://vesuvius-challenge-open-data/PHerc0139/segments/20250831000000-w040_2025083102",
|
| 72 |
"volume": "9.362um-1.2m-113keV-volume-20250728140407.zarr",
|
| 73 |
"voxel_um": 9.362,
|
| 74 |
+
"labels": {
|
| 75 |
+
"family": "native9-scrollprizeorg-21slices",
|
| 76 |
+
"segment": "w040",
|
| 77 |
+
"plane": 14
|
| 78 |
+
},
|
| 79 |
"origins_yx": null,
|
| 80 |
"provenance": {
|
| 81 |
"scroll": "PHerc0139",
|
|
|
|
| 91 |
"segment": "s3://vesuvius-challenge-open-data/PHerc0139/segments/20260108000000-w041_2026010816",
|
| 92 |
"volume": "9.362um-1.2m-113keV-volume-20250728140407.zarr",
|
| 93 |
"voxel_um": 9.362,
|
| 94 |
+
"labels": {
|
| 95 |
+
"family": "native9-scrollprizeorg-21slices",
|
| 96 |
+
"segment": "w041",
|
| 97 |
+
"plane": 14
|
| 98 |
+
},
|
| 99 |
"origins_yx": null,
|
| 100 |
"provenance": {
|
| 101 |
"scroll": "PHerc0139",
|
|
|
|
| 111 |
"segment": "s3://vesuvius-challenge-open-data/PHerc0139/segments/20260115000000-w044_2026011522",
|
| 112 |
"volume": "9.362um-1.2m-113keV-volume-20250728140407.zarr",
|
| 113 |
"voxel_um": 9.362,
|
| 114 |
+
"labels": {
|
| 115 |
+
"family": "native9-scrollprizeorg-21slices",
|
| 116 |
+
"segment": "w044",
|
| 117 |
+
"plane": 14
|
| 118 |
+
},
|
| 119 |
"origins_yx": null,
|
| 120 |
"provenance": {
|
| 121 |
"scroll": "PHerc0139",
|
|
|
|
| 127 |
{
|
| 128 |
"case": "pherc0841-w00",
|
| 129 |
"scroll": "PHerc0841",
|
| 130 |
+
"label": "PHerc0841 · w00 · 9,366 µm natif · annotations publiques par transfert 3D",
|
| 131 |
"segment": "s3://vesuvius-challenge-open-data/PHerc0841/segments/20260220213127-w00",
|
| 132 |
"volume": "9.366um-1.2m-113keV-volume-20250821151531.zarr",
|
| 133 |
"voxel_um": 9.366,
|
| 134 |
+
"labels": {
|
| 135 |
+
"kind": "mesh_transfer",
|
| 136 |
+
"root": "hf://buckets/scrollprize/datasets/ink/841/w00",
|
| 137 |
+
"labels": "w00_inklabels_v2.zarr",
|
| 138 |
+
"supervision": "w00_supervision_mask_v2.zarr",
|
| 139 |
+
"validation": "w00_validation_mask_v2.zarr",
|
| 140 |
+
"label_mesh": "hf://buckets/scrollprize/datasets/ink/841/w00",
|
| 141 |
+
"bridge_mesh": "s3://vesuvius-challenge-open-data/PHerc0841/segments/20260220213127-w00/mesh/20260220213127-on-20260319124803-2.403um-t2.tifxyz",
|
| 142 |
+
"label_voxel_um": 2.403,
|
| 143 |
+
"tolerance_um": 9.366,
|
| 144 |
+
"note": "annotations posées sur la surface 2,403 µm (15872 × 18944) ; tolérance = un pixel du modèle"
|
| 145 |
+
},
|
| 146 |
"origins_yx": null,
|
| 147 |
"provenance": {
|
| 148 |
"scroll": "PHerc0841",
|
src/candidates.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tri géométrique des composantes détectées : des mesures, jamais une lecture.
|
| 2 |
+
|
| 3 |
+
Chaque composante (seuil brut 0,5, ≥ 8 px, sens direct) reçoit des mesures de forme, de stabilité
|
| 4 |
+
(sens inversé, profondeur) et de cohérence avec le maillage 3D. Les portes de tri ne s'appliquent
|
| 5 |
+
qu'après un étalonnage sur des composantes annotées d'un rouleau hors entraînement ; il est écrit
|
| 6 |
+
une fois puis figé. Sans étalonnage, les mesures sont montrées sans verdict.
|
| 7 |
+
Aucun texte, glyphe ou transcription n'est produit ici.
|
| 8 |
+
"""
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import hashlib
|
| 12 |
+
import json
|
| 13 |
+
import math
|
| 14 |
+
import time
|
| 15 |
+
|
| 16 |
+
MAX_COMPONENTS = 400
|
| 17 |
+
FEATURES = ('area_px', 'mean_score', 'reverse_support', 'depth_spread_mean', 'elongation')
|
| 18 |
+
MIN_SAMPLES = 30 # composantes annotées « encre » et « sans encre » exigées pour étalonner
|
| 19 |
+
MIN_SEPARATION = 0.70 # AUC minimale (dans un sens ou l'autre) pour qu'une mesure devienne une porte
|
| 20 |
+
STRETCH_TOLERANCE = 0.20 # écart admis de l'étirement local du maillage autour de 1
|
| 21 |
+
GATES_FILE = 'candidate_gates_v1.json'
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _auc(values, truth):
|
| 25 |
+
"""Aire sous la courbe ROC par rangs moyens ; None si une classe manque."""
|
| 26 |
+
import numpy as np
|
| 27 |
+
from scipy.stats import rankdata
|
| 28 |
+
truth = np.asarray(truth, bool); values = np.asarray(values, 'float64')
|
| 29 |
+
positives, negatives = int(truth.sum()), int((~truth).sum())
|
| 30 |
+
if not positives or not negatives:
|
| 31 |
+
return None
|
| 32 |
+
ranks = rankdata(values)
|
| 33 |
+
return float((ranks[truth].sum() - positives * (positives + 1) / 2) / (positives * negatives))
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def measure(storage, folder, mesh=None, report=None):
|
| 37 |
+
"""Mesures de chaque composante d'une ROI archivée et mesures d'ensemble de la ROI."""
|
| 38 |
+
import numpy as np
|
| 39 |
+
import tifffile
|
| 40 |
+
from scipy.ndimage import find_objects, label
|
| 41 |
+
folder = storage.checked(folder, 'submissions')
|
| 42 |
+
read = lambda name: tifffile.imread(storage.checked(folder / name, 'submissions'))
|
| 43 |
+
if report is None:
|
| 44 |
+
report = json.loads(storage.checked(folder / 'metadata.json', 'submissions').read_text(encoding='utf-8'))
|
| 45 |
+
binary = read('forward.components.tif').astype(bool)
|
| 46 |
+
forward = np.nan_to_num(read('forward.probabilities.tif'), nan=0.).astype('float64')
|
| 47 |
+
reverse = np.nan_to_num(read('reverse.probabilities.tif'), nan=0.).astype('float64')
|
| 48 |
+
spread = np.nan_to_num(read('forward.depth_spread.tif'), nan=0.).astype('float64')
|
| 49 |
+
if not (binary.shape == forward.shape == reverse.shape == spread.shape == (512, 512)):
|
| 50 |
+
raise ValueError('artefacts de ROI incompatibles')
|
| 51 |
+
truth = mask = None
|
| 52 |
+
if (folder / 'labels.tif').is_file() and (folder / 'validation_mask.tif').is_file():
|
| 53 |
+
truth = read('labels.tif').astype(bool); mask = read('validation_mask.tif').astype(bool)
|
| 54 |
+
voxel = float(report['voxel_um']); origin = report['origin_yx']
|
| 55 |
+
numbered, count = label(binary, structure=np.ones((3, 3), bool))
|
| 56 |
+
sizes = np.bincount(numbered.ravel(), minlength=count + 1)
|
| 57 |
+
order = [i for i in np.argsort(-sizes) if i != 0 and sizes[i] > 0][:MAX_COMPONENTS]
|
| 58 |
+
boxes = find_objects(numbered)
|
| 59 |
+
rows = []
|
| 60 |
+
for rank, index in enumerate(order, 1):
|
| 61 |
+
box = boxes[index - 1]; inside = numbered[box] == index
|
| 62 |
+
ys, xs = np.nonzero(inside); ys = ys + box[0].start; xs = xs + box[1].start
|
| 63 |
+
cy, cx = float(ys.mean()), float(xs.mean())
|
| 64 |
+
if len(ys) > 1:
|
| 65 |
+
covariance = np.cov(np.stack([xs, ys]).astype('float64'), bias=True) + np.eye(2) / 12 # + variance d'un pixel
|
| 66 |
+
values, vectors = np.linalg.eigh(covariance)
|
| 67 |
+
major, minor = 4 * math.sqrt(values[1]), 4 * math.sqrt(values[0])
|
| 68 |
+
angle = math.degrees(math.atan2(vectors[1, 1], vectors[0, 1])) % 180
|
| 69 |
+
else:
|
| 70 |
+
major = minor = 4 * math.sqrt(1 / 12); angle = 0.
|
| 71 |
+
row = {'id': rank, 'label_index': int(index), 'area_px': int(len(ys)), 'centroid_yx': [round(cy, 1), round(cx, 1)],
|
| 72 |
+
'surface_yx': [round(origin[0] + cy, 1), round(origin[1] + cx, 1)],
|
| 73 |
+
'bbox_yx': [int(ys.min()), int(xs.min()), int(ys.max()) + 1, int(xs.max()) + 1],
|
| 74 |
+
'major_um': round(major * voxel, 1), 'minor_um': round(minor * voxel, 1),
|
| 75 |
+
'elongation': round(major / minor, 3), 'orientation_deg': round(angle, 1),
|
| 76 |
+
'mean_score': round(float(forward[ys, xs].mean()), 4),
|
| 77 |
+
'reverse_mean_score': round(float(reverse[ys, xs].mean()), 4),
|
| 78 |
+
'asymmetry': round(float(forward[ys, xs].mean() - reverse[ys, xs].mean()), 4),
|
| 79 |
+
'reverse_support': round(float((reverse[ys, xs] >= .5).mean()), 4),
|
| 80 |
+
'depth_spread_mean': round(float(spread[ys, xs].mean()), 4)}
|
| 81 |
+
stretch = None
|
| 82 |
+
if mesh is not None:
|
| 83 |
+
from .vc3d_bridge import local_stretch
|
| 84 |
+
stretch = local_stretch(mesh, origin[0] + cy, origin[1] + cx)
|
| 85 |
+
row['mesh_stretch_yx'] = None if stretch is None else [round(stretch[0], 3), round(stretch[1], 3)]
|
| 86 |
+
row['area_um2'] = round(len(ys) * voxel**2 * (stretch[0] * stretch[1] if stretch else 1.), 1)
|
| 87 |
+
row['area_basis'] = 'maillage 3D' if stretch else 'pixel nominal, maillage indisponible ici'
|
| 88 |
+
if truth is not None:
|
| 89 |
+
annotated = mask[ys, xs]
|
| 90 |
+
share = float(annotated.mean()); ink = float(truth[ys, xs][annotated].mean()) if annotated.any() else 0.
|
| 91 |
+
row['annotated_fraction'] = round(share, 3); row['annotated_ink_fraction'] = round(ink, 3)
|
| 92 |
+
row['truth'] = None if share < .5 else 'ink' if ink >= .5 else 'no_ink' if ink == 0 else 'mixed'
|
| 93 |
+
rows.append(row)
|
| 94 |
+
summary = {'components': int(count), 'components_listed': len(rows), 'voxel_um': voxel, 'origin_yx': origin,
|
| 95 |
+
'ink_fraction': float(binary.mean())}
|
| 96 |
+
if len(rows) >= 2:
|
| 97 |
+
centres = np.array([r['centroid_yx'] for r in rows])
|
| 98 |
+
distance = np.linalg.norm(centres[:, None] - centres[None], axis=-1); np.fill_diagonal(distance, np.inf)
|
| 99 |
+
summary['nearest_neighbour_spacing_um'] = round(float(np.median(distance.min(1))) * voxel, 1)
|
| 100 |
+
elongated = [r for r in rows if r['elongation'] >= 1.5]
|
| 101 |
+
if elongated:
|
| 102 |
+
# Moyenne circulaire sur 180°, pondérée par l'aire : orientation dominante des traits allongés.
|
| 103 |
+
angles = np.radians([2 * r['orientation_deg'] for r in elongated]); weights = np.array([r['area_px'] for r in elongated], float)
|
| 104 |
+
vector = np.array([(weights * np.cos(angles)).sum(), (weights * np.sin(angles)).sum()]) / weights.sum()
|
| 105 |
+
summary['dominant_orientation_deg'] = round(math.degrees(math.atan2(vector[1], vector[0])) / 2 % 180, 1)
|
| 106 |
+
summary['orientation_coherence'] = round(float(np.linalg.norm(vector)), 3)
|
| 107 |
+
for axis, name in ((1, 'row'), (0, 'column')):
|
| 108 |
+
profile = binary.sum(axis).astype('float64'); profile -= profile.mean()
|
| 109 |
+
if profile.any():
|
| 110 |
+
correlation = np.correlate(profile, profile, 'full')[len(profile) - 1:]; correlation /= correlation[0]
|
| 111 |
+
lags = np.arange(len(correlation)); window = (lags >= 8) & (lags <= 256)
|
| 112 |
+
peak = int(lags[window][np.argmax(correlation[window])])
|
| 113 |
+
summary[name + '_period_um'] = round(peak * voxel, 1); summary[name + '_period_strength'] = round(float(correlation[peak]), 3)
|
| 114 |
+
return rows, summary
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def load_gates(storage):
|
| 118 |
+
path = storage.path('chunks', GATES_FILE)
|
| 119 |
+
if not path.is_file():
|
| 120 |
+
return None
|
| 121 |
+
try:
|
| 122 |
+
gates = json.loads(path.read_text(encoding='utf-8'))
|
| 123 |
+
return gates if gates.get('schema') == 'unique-candidate-gates/1' else None
|
| 124 |
+
except (ValueError, OSError):
|
| 125 |
+
return None
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def calibrate(storage, rows, source):
|
| 129 |
+
"""Étalonnage unique : seuils de Youden par mesure, sur des composantes annotées. Jamais réécrit s'il existe."""
|
| 130 |
+
import numpy as np
|
| 131 |
+
existing = load_gates(storage)
|
| 132 |
+
if existing is not None:
|
| 133 |
+
return {**existing, 'frozen': True}
|
| 134 |
+
known = [r for r in rows if r.get('truth') in ('ink', 'no_ink')]
|
| 135 |
+
truth = np.array([r['truth'] == 'ink' for r in known], bool)
|
| 136 |
+
if truth.sum() < MIN_SAMPLES or (~truth).sum() < MIN_SAMPLES:
|
| 137 |
+
raise ValueError(f'étalonnage refusé : {int(truth.sum())} composantes « encre » et {int((~truth).sum())} « sans encre » annotées ; '
|
| 138 |
+
f'{MIN_SAMPLES} de chaque requises')
|
| 139 |
+
features = {}
|
| 140 |
+
for name in FEATURES:
|
| 141 |
+
values = np.array([r[name] for r in known], 'float64')
|
| 142 |
+
auc = _auc(values, truth)
|
| 143 |
+
sign = 1 if auc >= .5 else -1 # -1 : une valeur basse indique l'encre
|
| 144 |
+
best = (-1., None)
|
| 145 |
+
for threshold in np.unique(values):
|
| 146 |
+
passed = sign * values >= sign * threshold
|
| 147 |
+
youden = passed[truth].mean() - passed[~truth].mean()
|
| 148 |
+
if youden > best[0]:
|
| 149 |
+
best = (float(youden), float(threshold))
|
| 150 |
+
features[name] = {'auc': round(auc, 4), 'direction': 'min' if sign == 1 else 'max', 'threshold': best[1],
|
| 151 |
+
'youden_j': round(best[0], 4), 'used_as_gate': max(auc, 1 - auc) >= MIN_SEPARATION}
|
| 152 |
+
gates = {'schema': 'unique-candidate-gates/1', 'created_at': time.time(), 'source': source,
|
| 153 |
+
'ink_components': int(truth.sum()), 'no_ink_components': int((~truth).sum()), 'features': features,
|
| 154 |
+
'rule': 'une composante est retenue si elle passe toutes les mesures marquées used_as_gate et la porte du maillage 3D',
|
| 155 |
+
'stretch_tolerance': STRETCH_TOLERANCE, 'min_separation_auc': MIN_SEPARATION,
|
| 156 |
+
'scope': 'seuils choisis sur ces mêmes composantes : leur taux de réussite sur cette surface est optimiste',
|
| 157 |
+
'sample_sha256': hashlib.sha256(json.dumps([[r[n] for n in FEATURES] + [r['truth']] for r in known]).encode()).hexdigest()}
|
| 158 |
+
storage.json('chunks', GATES_FILE, gates)
|
| 159 |
+
return {**gates, 'frozen': False}
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def verdict(row, gates):
|
| 163 |
+
"""« retenu », « écarté » avec ses motifs, ou « non étalonné ». Ce n'est pas un verdict d'encre."""
|
| 164 |
+
if gates is None:
|
| 165 |
+
return 'non étalonné', []
|
| 166 |
+
reasons = []
|
| 167 |
+
for name, gate in gates['features'].items():
|
| 168 |
+
if not gate['used_as_gate']:
|
| 169 |
+
continue
|
| 170 |
+
ok = row[name] >= gate['threshold'] if gate['direction'] == 'min' else row[name] <= gate['threshold']
|
| 171 |
+
if not ok:
|
| 172 |
+
reasons.append(name + (' < ' if gate['direction'] == 'min' else ' > ') + format(gate['threshold'], 'g'))
|
| 173 |
+
stretch = row.get('mesh_stretch_yx')
|
| 174 |
+
if stretch is None:
|
| 175 |
+
reasons.append('maillage 3D incomplet autour de la composante')
|
| 176 |
+
elif any(abs(v - 1) > gates['stretch_tolerance'] for v in stretch):
|
| 177 |
+
reasons.append('surface étirée : ' + str(stretch))
|
| 178 |
+
return ('retenu' if not reasons else 'écarté'), reasons
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def overlay(ct, rows, numbered_binary, verdicts):
|
| 182 |
+
"""CT en gris avec le contour de chaque composante : vert retenu, rouge écarté, ambre non étalonné."""
|
| 183 |
+
import numpy as np
|
| 184 |
+
from scipy.ndimage import binary_dilation, binary_erosion, label
|
| 185 |
+
image = np.repeat(np.asarray(ct, 'uint8')[..., None], 3, axis=2)
|
| 186 |
+
numbered, _ = label(numbered_binary, structure=np.ones((3, 3), bool))
|
| 187 |
+
colours = {'retenu': (52, 211, 153), 'écarté': (248, 113, 113), 'non étalonné': (251, 191, 36)}
|
| 188 |
+
for row, state in zip(rows, verdicts):
|
| 189 |
+
shape = numbered == row['label_index'] # même étiquetage déterministe que measure()
|
| 190 |
+
edge = binary_dilation(shape, iterations=2) & ~binary_erosion(shape)
|
| 191 |
+
image[edge] = colours[state]
|
| 192 |
+
return image
|
src/label_transfer.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Transfert d'annotations publiques vers une surface d'une autre grille, par la géométrie 3D seule.
|
| 2 |
+
|
| 3 |
+
Cas visé : PHerc0841 w00. Les annotations publiques sont posées sur la surface rendue à 2,403 µm ;
|
| 4 |
+
le modèle lit la surface rendue à 9,366 µm, dont le repère plat est différent. Le passage se fait
|
| 5 |
+
uniquement par des maillages tifxyz publiés :
|
| 6 |
+
|
| 7 |
+
pixel 9,366 µm ──(grille « pont » : mêmes nœuds, coordonnées dans le volume 2,403 µm)──► point 3D
|
| 8 |
+
point 3D ──(projection sur le maillage des annotations, même volume)──► pixel de la grille annotée
|
| 9 |
+
|
| 10 |
+
Deux portes, déclarées avant toute mesure :
|
| 11 |
+
1. le pont doit avoir exactement la grille du maillage 9,366 µm, et s'en déduire par une
|
| 12 |
+
transformation affine à moins de TOLERANCE près (contrôle de cohérence des deux repères) ;
|
| 13 |
+
2. chaque pixel projeté doit tomber à moins de TOLERANCE du maillage annoté.
|
| 14 |
+
Si une porte échoue, aucune annotation n'est rendue : pas de métrique plutôt qu'une métrique décalée.
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import math
|
| 19 |
+
|
| 20 |
+
MIN_MAPPED_FRACTION = 0.95 # part minimale des pixels de la ROI projetés dans la tolérance
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class TransferRefused(ValueError):
|
| 24 |
+
"""Porte géométrique non franchie ; le message dit laquelle et de combien."""
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _affine_check(source, target, valid, unit_um):
|
| 28 |
+
"""Ajuste target ≈ [source,1]·M sur les nœuds valides ; renvoie facteurs d'échelle et résidus en µm."""
|
| 29 |
+
import numpy as np
|
| 30 |
+
a = source[valid].astype('float64'); b = target[valid].astype('float64')
|
| 31 |
+
if len(a) < 16:
|
| 32 |
+
raise TransferRefused('pont : moins de 16 nœuds communs')
|
| 33 |
+
design = np.concatenate([a, np.ones((len(a), 1))], axis=1)
|
| 34 |
+
matrix, *_ = np.linalg.lstsq(design, b, rcond=None)
|
| 35 |
+
residual = np.linalg.norm(design @ matrix - b, axis=1) * unit_um
|
| 36 |
+
# Rapport d'échelle des deux repères : dispersion des nœuds, indépendant de la courbure du maillage.
|
| 37 |
+
scale = math.sqrt(float(b.var(0).sum()) / max(float(a.var(0).sum()), 1e-12))
|
| 38 |
+
return {'nodes': int(len(a)), 'linear_scale': round(scale, 5),
|
| 39 |
+
'residual_p50_um': float(np.percentile(residual, 50)), 'residual_p95_um': float(np.percentile(residual, 95)),
|
| 40 |
+
'residual_max_um': float(residual.max())}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class Transfer:
|
| 44 |
+
"""Correspondance pixel plat de la surface du modèle → pixel de la grille annotée."""
|
| 45 |
+
|
| 46 |
+
def __init__(self, native, bridge, target, tolerance_um):
|
| 47 |
+
import numpy as np
|
| 48 |
+
from scipy.spatial import cKDTree
|
| 49 |
+
if bridge['grid_shape'] != native['grid_shape']:
|
| 50 |
+
raise TransferRefused('pont : grille ' + str(bridge['grid_shape']) + ' différente de celle du maillage natif ' + str(native['grid_shape']))
|
| 51 |
+
common = native['valid'] & bridge['valid']
|
| 52 |
+
if common.sum() < 0.98 * native['valid'].sum():
|
| 53 |
+
raise TransferRefused('pont : nœuds valides non concordants avec le maillage natif')
|
| 54 |
+
self.tolerance_um = float(tolerance_um)
|
| 55 |
+
self.affine = _affine_check(native['xyz'], bridge['xyz'], common, bridge['voxel_um'])
|
| 56 |
+
if self.affine['residual_p95_um'] > self.tolerance_um:
|
| 57 |
+
raise TransferRefused(f'pont : écart à une transformation affine p95 = {self.affine["residual_p95_um"]:.1f} µm > {self.tolerance_um} µm')
|
| 58 |
+
# Le pont porte l'échelle plate du maillage natif : mêmes nœuds, autre repère 3D.
|
| 59 |
+
self.bridge = {**bridge, 'scale_yx': native['scale_yx']}
|
| 60 |
+
self.target = target
|
| 61 |
+
rows, cols = np.nonzero(target['valid'])
|
| 62 |
+
self.nodes = np.stack([rows, cols], axis=1)
|
| 63 |
+
self.tree = cKDTree(target['xyz'][rows, cols].astype('float64'))
|
| 64 |
+
self.identity = {'native_mesh_sha256': native['sha256'], 'bridge_mesh_sha256': bridge['sha256'],
|
| 65 |
+
'label_mesh_sha256': target['sha256'], 'tolerance_um': self.tolerance_um}
|
| 66 |
+
|
| 67 |
+
def project(self, points_yx):
|
| 68 |
+
"""(N,2) pixels y,x de la surface du modèle → (N,2) pixels y,x annotés, résidu 3D en µm, masque de validité."""
|
| 69 |
+
import numpy as np
|
| 70 |
+
from .vc3d_bridge import interpolate
|
| 71 |
+
points, ok = interpolate(self.bridge, np.asarray(points_yx, dtype='float64'))
|
| 72 |
+
canvas = np.full((len(points), 2), np.nan); residual = np.full(len(points), np.inf)
|
| 73 |
+
if not ok.any():
|
| 74 |
+
return canvas, residual, ok
|
| 75 |
+
xyz, valid = self.target['xyz'].astype('float64'), self.target['valid']
|
| 76 |
+
_, nearest = self.tree.query(points[ok])
|
| 77 |
+
r, c = self.nodes[nearest, 0], self.nodes[nearest, 1]
|
| 78 |
+
rm, rp = np.maximum(r - 1, 0), np.minimum(r + 1, valid.shape[0] - 1)
|
| 79 |
+
cm, cp = np.maximum(c - 1, 0), np.minimum(c + 1, valid.shape[1] - 1)
|
| 80 |
+
usable = valid[rm, c] & valid[rp, c] & valid[r, cm] & valid[r, cp] & (rp > rm) & (cp > cm)
|
| 81 |
+
ev = (xyz[rp, c] - xyz[rm, c]) / np.maximum(rp - rm, 1)[:, None] # tangente par pas de grille en y
|
| 82 |
+
eu = (xyz[r, cp] - xyz[r, cm]) / np.maximum(cp - cm, 1)[:, None] # tangente par pas de grille en x
|
| 83 |
+
delta = points[ok] - xyz[r, c]
|
| 84 |
+
a, b, d = (ev * ev).sum(1), (ev * eu).sum(1), (eu * eu).sum(1)
|
| 85 |
+
p, q = (delta * ev).sum(1), (delta * eu).sum(1)
|
| 86 |
+
det = a * d - b * b
|
| 87 |
+
usable &= det > 1e-9
|
| 88 |
+
det = np.where(usable, det, 1.)
|
| 89 |
+
dv = (p * d - q * b) / det; du = (q * a - p * b) / det
|
| 90 |
+
usable &= (np.abs(dv) <= 1.5) & (np.abs(du) <= 1.5)
|
| 91 |
+
distance = np.linalg.norm(delta - dv[:, None] * ev - du[:, None] * eu, axis=1) * self.target['voxel_um']
|
| 92 |
+
sy, sx = self.target['scale_yx']
|
| 93 |
+
index = np.flatnonzero(ok)
|
| 94 |
+
canvas[index] = np.stack([(r + dv) / sy, (c + du) / sx], axis=1)
|
| 95 |
+
residual[index] = np.where(usable, distance, np.inf)
|
| 96 |
+
good = np.zeros(len(points), bool); good[index] = usable & (distance <= self.tolerance_um)
|
| 97 |
+
return canvas, residual, good
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def build(storage, stream, item):
|
| 101 |
+
"""Charge les trois maillages et vérifie la première porte ; lève TransferRefused sinon."""
|
| 102 |
+
from .vc3d_bridge import load_tifxyz, load_tifxyz_uri
|
| 103 |
+
spec = item['labels']
|
| 104 |
+
native = load_tifxyz(storage, stream, item)
|
| 105 |
+
bridge = load_tifxyz_uri(storage, stream, spec['bridge_mesh'], spec['label_voxel_um'])
|
| 106 |
+
target = load_tifxyz_uri(storage, stream, spec['label_mesh'], spec['label_voxel_um'])
|
| 107 |
+
return Transfer(native, bridge, target, spec['tolerance_um'])
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def _read_plane(stream, uri, canvas, good):
|
| 111 |
+
"""Valeur annotée la plus proche de chaque pixel projeté, au plus fin niveau de pyramide qui tient dans le budget."""
|
| 112 |
+
import numpy as np
|
| 113 |
+
for level in ('0', '1', '2'):
|
| 114 |
+
meta = stream.probe(uri, levels=(level,))['levels'][0]
|
| 115 |
+
scale = meta['scale_zyx'] or ([1., 1., 1.] if level == '0' else None)
|
| 116 |
+
if scale is None or scale[1] != scale[2]:
|
| 117 |
+
continue
|
| 118 |
+
factor = scale[1]
|
| 119 |
+
index = np.floor(canvas[good] / factor + (.5 if factor == 1 else 0)).astype(int)
|
| 120 |
+
inside = (index >= 0).all(1) & (index[:, 0] < meta['shape'][1]) & (index[:, 1] < meta['shape'][2])
|
| 121 |
+
if not inside.any():
|
| 122 |
+
return None, None, {'uri': uri, 'level': level, 'reason': 'projection hors de la grille annotée'}
|
| 123 |
+
low = index[inside].min(0); high = index[inside].max(0) + 1
|
| 124 |
+
origin = [0, int(low[0]), int(low[1])]; shape = [int(meta['shape'][0]), int(high[0] - low[0]), int(high[1] - low[1])]
|
| 125 |
+
touched = math.prod((o + n - 1) // c - o // c + 1 for o, n, c in zip(origin, shape, meta['chunks']))
|
| 126 |
+
if touched * math.prod(meta['chunks']) > stream.raw_limit and level != '2':
|
| 127 |
+
continue
|
| 128 |
+
data, info = stream.window(uri, level, origin, shape)
|
| 129 |
+
planes = np.flatnonzero(data.reshape(data.shape[0], -1).any(1)).tolist()
|
| 130 |
+
flat = data.max(0) # annotations portées par un plan ; les autres plans sont vides
|
| 131 |
+
values = np.zeros(len(index), dtype=flat.dtype)
|
| 132 |
+
values[inside] = flat[index[inside, 0] - low[0], index[inside, 1] - low[1]]
|
| 133 |
+
return values, inside, {'uri': uri, 'level': level, 'sha256': info['sha256'], 'network_bytes': info['network_bytes'],
|
| 134 |
+
'chunks_touched': info['chunks_touched'], 'from_cache': info['from_cache'],
|
| 135 |
+
'window_zyx': shape, 'planes_with_data': planes[:8]}
|
| 136 |
+
raise TransferRefused('fenêtre d’annotations trop large pour le budget de lecture')
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def transfer(storage, stream, item, origin, size=512):
|
| 140 |
+
"""Annotations et masque de mesure de la ROI dans la grille du modèle, avec le rapport des portes.
|
| 141 |
+
|
| 142 |
+
Renvoie (labels, mask, rapport). Lève TransferRefused si une porte géométrique échoue.
|
| 143 |
+
"""
|
| 144 |
+
import numpy as np
|
| 145 |
+
from .surface_manifest import _binary
|
| 146 |
+
spec = item['labels']
|
| 147 |
+
mapping = build(storage, stream, item)
|
| 148 |
+
yy, xx = np.mgrid[0:size, 0:size]
|
| 149 |
+
points = np.stack([origin[0] + yy.ravel(), origin[1] + xx.ravel()], axis=1)
|
| 150 |
+
canvas, residual, good = mapping.project(points)
|
| 151 |
+
fraction = float(good.mean())
|
| 152 |
+
finite = residual[np.isfinite(residual)]
|
| 153 |
+
gate = {'bridge_affine': mapping.affine, 'tolerance_um': mapping.tolerance_um, 'mapped_fraction': fraction,
|
| 154 |
+
'minimum_mapped_fraction': MIN_MAPPED_FRACTION,
|
| 155 |
+
'residual_p50_um': float(np.percentile(finite, 50)) if finite.size else None,
|
| 156 |
+
'residual_p95_um': float(np.percentile(finite, 95)) if finite.size else None, **mapping.identity}
|
| 157 |
+
if fraction < MIN_MAPPED_FRACTION:
|
| 158 |
+
raise TransferRefused(f'projection : {100 * fraction:.1f} % des pixels à moins de {mapping.tolerance_um} µm du maillage annoté '
|
| 159 |
+
f'(minimum {100 * MIN_MAPPED_FRACTION:.0f} %) ; p95 du résidu = {gate["residual_p95_um"]} µm')
|
| 160 |
+
arrays = {}; evidence = []
|
| 161 |
+
for role in ('labels', 'supervision', 'validation'):
|
| 162 |
+
if not spec.get(role):
|
| 163 |
+
continue
|
| 164 |
+
values, inside, info = _read_plane(stream, spec['root'] + '/' + spec[role], canvas, good)
|
| 165 |
+
if values is None:
|
| 166 |
+
raise TransferRefused(info['reason'])
|
| 167 |
+
full = np.zeros(size * size, 'uint8'); known = np.zeros(size * size, bool)
|
| 168 |
+
index = np.flatnonzero(good)
|
| 169 |
+
full[index[inside]] = _binary(values[inside], role); known[index[inside]] = True
|
| 170 |
+
arrays[role] = (full.reshape(size, size), known.reshape(size, size))
|
| 171 |
+
evidence.append({'role': role, **info})
|
| 172 |
+
labels, known = arrays['labels']
|
| 173 |
+
annotated = np.zeros((size, size), bool)
|
| 174 |
+
for role in ('supervision', 'validation'):
|
| 175 |
+
if role in arrays:
|
| 176 |
+
annotated |= arrays[role][0].astype(bool) & arrays[role][1]
|
| 177 |
+
gate[role + '_pixels'] = int((arrays[role][0].astype(bool) & arrays[role][1]).sum())
|
| 178 |
+
mask = (annotated & known).astype('uint8')
|
| 179 |
+
gate.update(annotated_pixels=int(mask.sum()), positive_pixels=int((labels.astype(bool) & mask.astype(bool)).sum()),
|
| 180 |
+
mask_rule='supervision ∪ validation publiques, restreintes aux pixels projetés dans la tolérance')
|
| 181 |
+
return labels, mask, {'gate': gate, 'evidence': evidence}
|
src/multi_surface.py
CHANGED
|
@@ -15,6 +15,7 @@ COLUMNS = ['case', 'scroll', 'origin_yx', 'status', 'engine', 'fallback', 'prove
|
|
| 15 |
'valid_fraction', 'ink_fraction_forward', 'ink_fraction_reverse', 'components_forward', 'components_reverse',
|
| 16 |
'depth_spread_mean', 'depth_spread_p95', 'w8_mean_abs_error', 'w8_max_abs_error', 'w8_threshold_flips',
|
| 17 |
'tp', 'fp', 'fn', 'tn', 'precision', 'recall', 'f0_5', 'false_positive_rate', 'auc',
|
|
|
|
| 18 |
'network_bytes', 'seconds', 'archive', 'error']
|
| 19 |
|
| 20 |
|
|
@@ -42,6 +43,11 @@ def summarize(storage, case, scroll, report, folder):
|
|
| 42 |
row['w8_mean_abs_error'] = max(float(d['mean_absolute_score_error']) for d in gap.values())
|
| 43 |
row['w8_max_abs_error'] = max(float(d['max_absolute_score_error']) for d in gap.values())
|
| 44 |
row['w8_threshold_flips'] = int(sum(d['threshold_flips'] for d in gap.values()))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
confusion = (report.get('metrics') or {}).get('forward', {}).get('raw')
|
| 46 |
if confusion:
|
| 47 |
row.update({k: confusion[k] for k in ('tp', 'fp', 'fn', 'tn', 'precision', 'recall', 'f0_5', 'false_positive_rate')})
|
|
@@ -116,7 +122,8 @@ def run(storage, cases=None, tiles=1, radius=1, quantization='auto8', device='cu
|
|
| 116 |
'rois_failed': len(rows) - len(done), 'scrolls': sorted({r['scroll'] for r in done}),
|
| 117 |
'threshold_raw': .5, 'min_component_area': 8, 'seconds': time.monotonic() - started, 'logs': events,
|
| 118 |
'roi_selection': 'plan gelé, indépendant des prédictions',
|
| 119 |
-
'limitations': ['Les surfaces annotées sont des données d’entraînement du checkpoint : leurs métriques sont internes, pas une validation.',
|
|
|
|
| 120 |
'Sans annotation, seules des statistiques de sortie sont consignées ; elles ne mesurent pas la justesse.',
|
| 121 |
'Aucune lecture humaine, transcription ni certification de lisibilité.'],
|
| 122 |
'held_out_evaluated': False, 'legibility_certified': False, 'submission_ready': False}
|
|
|
|
| 15 |
'valid_fraction', 'ink_fraction_forward', 'ink_fraction_reverse', 'components_forward', 'components_reverse',
|
| 16 |
'depth_spread_mean', 'depth_spread_p95', 'w8_mean_abs_error', 'w8_max_abs_error', 'w8_threshold_flips',
|
| 17 |
'tp', 'fp', 'fn', 'tn', 'precision', 'recall', 'f0_5', 'false_positive_rate', 'auc',
|
| 18 |
+
'transfer_residual_p95_um', 'transfer_mapped_fraction', 'transfer_refused', 'annotated_pixels', 'positive_pixels',
|
| 19 |
'network_bytes', 'seconds', 'archive', 'error']
|
| 20 |
|
| 21 |
|
|
|
|
| 43 |
row['w8_mean_abs_error'] = max(float(d['mean_absolute_score_error']) for d in gap.values())
|
| 44 |
row['w8_max_abs_error'] = max(float(d['max_absolute_score_error']) for d in gap.values())
|
| 45 |
row['w8_threshold_flips'] = int(sum(d['threshold_flips'] for d in gap.values()))
|
| 46 |
+
transfer = (report.get('surface') or {}).get('label_transfer')
|
| 47 |
+
if transfer:
|
| 48 |
+
row['transfer_refused'] = transfer.get('refused')
|
| 49 |
+
row['transfer_residual_p95_um'] = transfer.get('residual_p95_um'); row['transfer_mapped_fraction'] = transfer.get('mapped_fraction')
|
| 50 |
+
row['annotated_pixels'] = transfer.get('annotated_pixels'); row['positive_pixels'] = transfer.get('positive_pixels')
|
| 51 |
confusion = (report.get('metrics') or {}).get('forward', {}).get('raw')
|
| 52 |
if confusion:
|
| 53 |
row.update({k: confusion[k] for k in ('tp', 'fp', 'fn', 'tn', 'precision', 'recall', 'f0_5', 'false_positive_rate')})
|
|
|
|
| 122 |
'rois_failed': len(rows) - len(done), 'scrolls': sorted({r['scroll'] for r in done}),
|
| 123 |
'threshold_raw': .5, 'min_component_area': 8, 'seconds': time.monotonic() - started, 'logs': events,
|
| 124 |
'roi_selection': 'plan gelé, indépendant des prédictions',
|
| 125 |
+
'limitations': ['Les surfaces annotées de PHerc0139 sont des données d’entraînement du checkpoint : leurs métriques sont internes, pas une validation.',
|
| 126 |
+
'PHerc0841 w00 : annotations publiques d’un rouleau absent de la fiche du modèle, transférées par la géométrie 3D ; mesure indépendante mais non certifiée, limitée aux ROI du plan.',
|
| 127 |
'Sans annotation, seules des statistiques de sortie sont consignées ; elles ne mesurent pas la justesse.',
|
| 128 |
'Aucune lecture humaine, transcription ni certification de lisibilité.'],
|
| 129 |
'held_out_evaluated': False, 'legibility_certified': False, 'submission_ready': False}
|
src/production_ui.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
"""Panneau de production 4.22 : sources distantes, boucle multi-surfaces et maillage 3D réel.
|
| 2 |
|
| 3 |
Tout ce qui part vers le navigateur est borné : maillage ≤ 20 000 sommets, images ≤ 512 px,
|
| 4 |
tableaux ≤ 64 lignes. Les lectures réseau passent par src.hub_stream (fenêtres et petits fichiers).
|
|
@@ -8,9 +8,14 @@ import json
|
|
| 8 |
import time
|
| 9 |
|
| 10 |
MAX_ROWS = 64
|
| 11 |
-
LOOP_HEADERS = ['Surface', '
|
| 12 |
-
'Encre ≥0,5 %
|
| 13 |
-
'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
PROBE_HEADERS = ['Surface', 'CT z×y×x', 'Blocs', 'Volume décompressé', 'Échelle µm', 'Annotations', 'Maillage tifxyz', 'État']
|
| 15 |
|
| 16 |
|
|
@@ -35,7 +40,17 @@ def probe_rows(storage, stream=None):
|
|
| 35 |
row[1] = ' × '.join(str(v) for v in level['shape']); row[2] = ' × '.join(str(v) for v in level['chunks'])
|
| 36 |
row[3] = _size(level['raw_bytes'])
|
| 37 |
row[4] = 'non déclarée' if level['scale_zyx'] is None else ' × '.join(format(v, 'g') for v in level['scale_zyx'])
|
| 38 |
-
if item.get('labels'):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
shape = stream.probe(label_uris(item)['labels'])['levels'][0]['shape']
|
| 40 |
row[5] = ' × '.join(str(v) for v in shape) + (' · alignées' if shape[1:] == level['shape'][1:] else ' · GRILLE DIFFÉRENTE')
|
| 41 |
else:
|
|
@@ -55,14 +70,19 @@ def probe_rows(storage, stream=None):
|
|
| 55 |
def loop_rows(rows):
|
| 56 |
table = []
|
| 57 |
for r in list(rows)[-MAX_ROWS:]:
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
None if r.get('components_forward') is None else str(r['components_forward']) + ' / ' + str(r.get('components_reverse')),
|
| 62 |
None if r.get('depth_spread_mean') is None else round(r['depth_spread_mean'], 4),
|
| 63 |
-
None if r.get('w8_max_abs_error') is None else round(r['w8_max_abs_error'],
|
| 64 |
-
|
| 65 |
-
r.get('
|
|
|
|
| 66 |
return table
|
| 67 |
|
| 68 |
|
|
@@ -115,33 +135,122 @@ def roi_scores(storage, folder_name):
|
|
| 115 |
return np.clip((np.nan_to_num(raw, nan=.25) - .25) / .5, 0, 1).astype('float32'), ct
|
| 116 |
|
| 117 |
|
| 118 |
-
def
|
| 119 |
-
"""Figure 3D bornée et note de traçabilité ; roi = nom du dossier d'une ROI analysée, ou None."""
|
| 120 |
from .hub_stream import Stream
|
| 121 |
from .surface_manifest import entry, surface_contract
|
| 122 |
-
from .vc3d_bridge import
|
| 123 |
item = entry(case); stream = stream or Stream(storage)
|
| 124 |
mesh = load_tifxyz(storage, stream, item)
|
| 125 |
try:
|
| 126 |
shape = surface_contract(stream, item)['shape'][1:]
|
| 127 |
except (ValueError, OSError):
|
| 128 |
shape = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
regions = analysed_rois(storage, case)
|
| 130 |
-
overlay = None; images = (None, None)
|
| 131 |
chosen = next((r for r in regions if r['folder'] == roi), None)
|
|
|
|
| 132 |
if chosen is not None:
|
| 133 |
-
|
| 134 |
-
overlay = {'origin_yx': chosen['origin_yx'], 'scores': scores}
|
| 135 |
-
images = (ct, (scores * 255).astype('uint8'))
|
| 136 |
fig, summary = figure(mesh, shape, regions, overlay, item['label'])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
note = ('**' + html.escape(item['label']) + '** — maillage public `' + html.escape(mesh['uri'].rsplit('/', 1)[-1]) + '`. \n'
|
| 138 |
f'Grille **{mesh["grid_shape"][1]} × {mesh["grid_shape"][0]}** points, **{100 * mesh["valid_fraction"]:.1f} %** valides ; '
|
| 139 |
f'envoyé au navigateur : **{summary["vertices_sent"]:,} sommets, {summary["faces_sent"]:,} triangles** (un point sur {summary["stride"]}). \n'
|
| 140 |
'Coordonnées : voxels du volume CT × taille de voxel du manifeste, en mm. '
|
| 141 |
'Lien repère plat ↔ 3D : **' + summary['flat_to_3d_link'] + '**. \n'
|
| 142 |
-
f'ROI analysées placées : **{summary["regions_placed"]}**' + (f' · hors maillage : {summary["regions_outside_mesh"]}' if summary['regions_outside_mesh'] else '')
|
| 143 |
-
|
| 144 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
|
| 146 |
|
| 147 |
def build_production(controller, authorized, secret):
|
|
@@ -174,19 +283,32 @@ def build_production(controller, authorized, secret):
|
|
| 174 |
loop_stop = gr.Button('Arrêter la boucle')
|
| 175 |
loop_reload = gr.Button('Recharger le dernier résumé')
|
| 176 |
loop_status = gr.Markdown('Aucune boucle lancée dans cette session.')
|
| 177 |
-
loop_table = gr.Dataframe(headers=LOOP_HEADERS, row_count=0, interactive=False,
|
| 178 |
label='Une ligne par ROI · seuil brut 0,5 · composantes ≥ 8 px')
|
| 179 |
loop_download = gr.HTML()
|
| 180 |
-
gr.Markdown('#### 3 · Maillage 3D réel et
|
| 181 |
with gr.Row():
|
| 182 |
-
mesh_case = gr.Dropdown(choices, value=choices[
|
| 183 |
-
mesh_roi = gr.Dropdown([('Aucune
|
| 184 |
-
|
| 185 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 186 |
mesh_note = gr.Markdown('Le maillage se charge à la demande.')
|
|
|
|
|
|
|
|
|
|
| 187 |
with gr.Row():
|
| 188 |
-
|
| 189 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
|
| 191 |
def view(report, folder, prefix=''):
|
| 192 |
link = ''
|
|
@@ -197,9 +319,12 @@ def build_production(controller, authorized, secret):
|
|
| 197 |
link = '<a class="download-result" href="/gradio/vesuvius-download/' + name + '" download="' + name + '">Télécharger le résumé de la boucle (JSON + CSV)</a>'
|
| 198 |
except (ValueError, OSError):
|
| 199 |
pass
|
|
|
|
| 200 |
text = (prefix + f'**{report["rois_done"]} ROI terminée(s) sur {report["rois_requested"]}**, {report["rois_failed"]} en échec · '
|
| 201 |
'rouleaux : ' + (', '.join(report['scrolls']) or 'aucun') + f' · {report["seconds"]:.0f} s. \n'
|
| 202 |
-
'
|
|
|
|
|
|
|
| 203 |
return text, loop_rows(report['rows']), link
|
| 204 |
|
| 205 |
def probe(key, request: gr.Request):
|
|
@@ -252,16 +377,37 @@ def build_production(controller, authorized, secret):
|
|
| 252 |
def load_mesh(key, case, roi, request: gr.Request):
|
| 253 |
guard(key, request)
|
| 254 |
try:
|
| 255 |
-
fig,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
except (ValueError, OSError) as exc:
|
| 257 |
-
return
|
| 258 |
-
options = [('Aucune nappe de scores', '')] + [(r['label'], r['folder']) for r in regions[:MAX_ROWS]]
|
| 259 |
-
return fig, note, ct, score, gr.update(choices=options, value=roi if any(roi == v for _, v in options) else '')
|
| 260 |
|
| 261 |
probe_button.click(probe, [secret], [probe_table], concurrency_limit=1, **private_event())
|
| 262 |
loop_button.click(launch, [secret, loop_cases, loop_tiles, loop_radius, loop_device],
|
| 263 |
[loop_status, loop_table, loop_download], concurrency_limit=None, **private_event())
|
| 264 |
loop_stop.click(stop, [secret], [loop_status], queue=False, **private_event())
|
| 265 |
loop_reload.click(reload, [secret], [loop_status, loop_table, loop_download], queue=False, **private_event())
|
| 266 |
-
mesh_button.click(load_mesh, [secret, mesh_case, mesh_roi], [mesh_plot,
|
| 267 |
concurrency_limit=1, **private_event())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Panneau de production (4.22, enrichi en 4.23) : sources distantes, boucle multi-surfaces et maillage 3D réel.
|
| 2 |
|
| 3 |
Tout ce qui part vers le navigateur est borné : maillage ≤ 20 000 sommets, images ≤ 512 px,
|
| 4 |
tableaux ≤ 64 lignes. Les lectures réseau passent par src.hub_stream (fenêtres et petits fichiers).
|
|
|
|
| 8 |
import time
|
| 9 |
|
| 10 |
MAX_ROWS = 64
|
| 11 |
+
LOOP_HEADERS = ['Surface', 'Origine y,x', 'État', 'Moteur', 'Données', 'Annotations', 'Précision %', 'Rappel %', 'F₀,₅ %',
|
| 12 |
+
'FPR %', 'AUC', 'Encre ≥0,5 %', 'Composantes', 'Sensib. prof.', 'Écart W8 max', 'Bascules W8',
|
| 13 |
+
'Transfert 3D p95 µm', 'CT valide %', 'Mio reçus', 'Durée s', 'Motif']
|
| 14 |
+
PROVENANCE = {'used_in_checkpoint_training': 'entraînement', 'used_in_checkpoint_training_other_representation': 'entraînement (autre représentation)',
|
| 15 |
+
'not_listed': 'hors fiche du modèle', 'unknown': 'inconnue'}
|
| 16 |
+
ROLES = {'training_supervision': 'supervision d’entraînement', 'no_annotation': 'aucune', 'independent_public_annotation': 'publiques · indépendantes',
|
| 17 |
+
'label_transfer_refused': 'transfert 3D refusé', 'label_grid_mismatch': 'grille différente', 'no_supervised_pixel_in_roi': 'aucun pixel annoté',
|
| 18 |
+
'public_online_validation': 'validation publique'}
|
| 19 |
PROBE_HEADERS = ['Surface', 'CT z×y×x', 'Blocs', 'Volume décompressé', 'Échelle µm', 'Annotations', 'Maillage tifxyz', 'État']
|
| 20 |
|
| 21 |
|
|
|
|
| 40 |
row[1] = ' × '.join(str(v) for v in level['shape']); row[2] = ' × '.join(str(v) for v in level['chunks'])
|
| 41 |
row[3] = _size(level['raw_bytes'])
|
| 42 |
row[4] = 'non déclarée' if level['scale_zyx'] is None else ' × '.join(format(v, 'g') for v in level['scale_zyx'])
|
| 43 |
+
if (item.get('labels') or {}).get('kind') == 'mesh_transfer':
|
| 44 |
+
spec = item['labels']
|
| 45 |
+
shape = stream.probe(spec['root'] + '/' + spec['labels'])['levels'][0]['shape']
|
| 46 |
+
try:
|
| 47 |
+
from .label_transfer import build
|
| 48 |
+
check = build(storage, stream, item).affine
|
| 49 |
+
row[5] = (' × '.join(str(v) for v in shape) + f' · autre grille · pont 3D vérifié (p95 {check["residual_p95_um"]:.2f} µm, '
|
| 50 |
+
f'échelle {check["linear_scale"]:g})')
|
| 51 |
+
except (ValueError, OSError) as exc:
|
| 52 |
+
row[5] = ' × '.join(str(v) for v in shape) + ' · autre grille · PONT 3D REFUSÉ : ' + str(exc)[:140]
|
| 53 |
+
elif item.get('labels'):
|
| 54 |
shape = stream.probe(label_uris(item)['labels'])['levels'][0]['shape']
|
| 55 |
row[5] = ' × '.join(str(v) for v in shape) + (' · alignées' if shape[1:] == level['shape'][1:] else ' · GRILLE DIFFÉRENTE')
|
| 56 |
else:
|
|
|
|
| 70 |
def loop_rows(rows):
|
| 71 |
table = []
|
| 72 |
for r in list(rows)[-MAX_ROWS:]:
|
| 73 |
+
engine = r.get('engine') or ''
|
| 74 |
+
table.append([str(r.get('case', '')).replace('native9-', '').replace('published-', '').replace('pherc0841-', '0841 '),
|
| 75 |
+
str(r.get('origin_yx', '')), {'done': 'terminé', 'error': 'échec', 'plan_error': 'plan impossible'}.get(r.get('status'), r.get('status')),
|
| 76 |
+
('référence (W8 refusé)' if r.get('fallback') else engine), PROVENANCE.get(r.get('provenance'), r.get('provenance')),
|
| 77 |
+
ROLES.get(r.get('labels_role'), r.get('labels_role')),
|
| 78 |
+
_pct(r.get('precision')), _pct(r.get('recall')), _pct(r.get('f0_5')), _pct(r.get('false_positive_rate'), 3),
|
| 79 |
+
None if r.get('auc') is None else round(r['auc'], 4), _pct(r.get('ink_fraction_forward'), 2),
|
| 80 |
None if r.get('components_forward') is None else str(r['components_forward']) + ' / ' + str(r.get('components_reverse')),
|
| 81 |
None if r.get('depth_spread_mean') is None else round(r['depth_spread_mean'], 4),
|
| 82 |
+
None if r.get('w8_max_abs_error') is None else round(r['w8_max_abs_error'], 4), r.get('w8_threshold_flips'),
|
| 83 |
+
None if r.get('transfer_residual_p95_um') is None else round(r['transfer_residual_p95_um'], 2),
|
| 84 |
+
_pct(r.get('valid_fraction'), 1), None if r.get('network_bytes') is None else round(r['network_bytes'] / 1024**2, 1),
|
| 85 |
+
r.get('seconds'), r.get('error') or r.get('transfer_refused') or ''])
|
| 86 |
return table
|
| 87 |
|
| 88 |
|
|
|
|
| 135 |
return np.clip((np.nan_to_num(raw, nan=.25) - .25) / .5, 0, 1).astype('float32'), ct
|
| 136 |
|
| 137 |
|
| 138 |
+
def _context(storage, case, stream=None):
|
|
|
|
| 139 |
from .hub_stream import Stream
|
| 140 |
from .surface_manifest import entry, surface_contract
|
| 141 |
+
from .vc3d_bridge import load_tifxyz
|
| 142 |
item = entry(case); stream = stream or Stream(storage)
|
| 143 |
mesh = load_tifxyz(storage, stream, item)
|
| 144 |
try:
|
| 145 |
shape = surface_contract(stream, item)['shape'][1:]
|
| 146 |
except (ValueError, OSError):
|
| 147 |
shape = None
|
| 148 |
+
return item, mesh, shape
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def mesh_view(storage, case, roi=None, stream=None):
|
| 152 |
+
"""Vue d'ensemble 3D, plan de situation plat et note ; roi = dossier d'une ROI analysée, ou None."""
|
| 153 |
+
from .vc3d_bridge import figure, grid_matches_surface, locator_figure
|
| 154 |
+
item, mesh, shape = _context(storage, case, stream)
|
| 155 |
regions = analysed_rois(storage, case)
|
|
|
|
| 156 |
chosen = next((r for r in regions if r['folder'] == roi), None)
|
| 157 |
+
overlay = None
|
| 158 |
if chosen is not None:
|
| 159 |
+
overlay = {'origin_yx': chosen['origin_yx'], 'scores': roi_scores(storage, chosen['folder'])[0]}
|
|
|
|
|
|
|
| 160 |
fig, summary = figure(mesh, shape, regions, overlay, item['label'])
|
| 161 |
+
locator = None
|
| 162 |
+
if shape is not None and grid_matches_surface(mesh, shape):
|
| 163 |
+
locator = locator_figure(mesh, shape, regions, chosen['origin_yx'] if chosen else None, 'Repère plat · ROI numérotées')
|
| 164 |
+
legend = ' · '.join(str(r['number']) + ' = y,x ' + str(r['origin_yx']) for r in summary['numbered'][:16])
|
| 165 |
note = ('**' + html.escape(item['label']) + '** — maillage public `' + html.escape(mesh['uri'].rsplit('/', 1)[-1]) + '`. \n'
|
| 166 |
f'Grille **{mesh["grid_shape"][1]} × {mesh["grid_shape"][0]}** points, **{100 * mesh["valid_fraction"]:.1f} %** valides ; '
|
| 167 |
f'envoyé au navigateur : **{summary["vertices_sent"]:,} sommets, {summary["faces_sent"]:,} triangles** (un point sur {summary["stride"]}). \n'
|
| 168 |
'Coordonnées : voxels du volume CT × taille de voxel du manifeste, en mm. '
|
| 169 |
'Lien repère plat ↔ 3D : **' + summary['flat_to_3d_link'] + '**. \n'
|
| 170 |
+
f'ROI analysées placées : **{summary["regions_placed"]}**' + (f' · hors maillage : {summary["regions_outside_mesh"]}' if summary['regions_outside_mesh'] else '')
|
| 171 |
+
+ (' \n' + legend if legend else '') + ' \n'
|
| 172 |
+
'Ambre : ROI analysée · bleu : ROI ouverte. Aucune paramétrisation UV n’est calculée ; une maille incomplète n’est jamais comblée.')
|
| 173 |
+
return fig, locator, note, regions
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
COMPONENT_HEADERS = ['N°', 'Tri', 'Motifs', 'Aire µm²', 'Grand axe µm', 'Allongement', 'Orientation °', 'Score moyen',
|
| 177 |
+
'Appui sens inversé %', 'Asymétrie', 'Sensib. prof.', 'Étirement maillage y·x', 'Annotation publique']
|
| 178 |
+
TRUTH = {'ink': 'encre', 'no_ink': 'sans encre', 'mixed': 'mixte', None: '—'}
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def dossier_view(storage, case, roi, stream=None):
|
| 182 |
+
"""Dossier technique d'une ROI : vue 3D rapprochée, images, composantes mesurées et triées. Aucune lecture."""
|
| 183 |
+
import numpy as np
|
| 184 |
+
import tifffile
|
| 185 |
+
from PIL import Image
|
| 186 |
+
from .candidates import load_gates, measure, overlay, verdict
|
| 187 |
+
from .vc3d_bridge import grid_matches_surface, roi_figure
|
| 188 |
+
item, mesh, shape = _context(storage, case, stream)
|
| 189 |
+
chosen = next((r for r in analysed_rois(storage, case) if r['folder'] == roi), None)
|
| 190 |
+
if chosen is None:
|
| 191 |
+
raise ValueError('choisir une ROI analysée de cette surface')
|
| 192 |
+
folder = storage.checked(storage.folder('submissions') / chosen['folder'], 'submissions')
|
| 193 |
+
report = json.loads(storage.checked(folder / 'metadata.json', 'submissions').read_text(encoding='utf-8'))
|
| 194 |
+
linked = shape is not None and grid_matches_surface(mesh, shape)
|
| 195 |
+
rows, summary = measure(storage, folder, mesh if linked else None, report)
|
| 196 |
+
gates = load_gates(storage)
|
| 197 |
+
states = [verdict(r, gates) for r in rows]
|
| 198 |
+
scores, ct = roi_scores(storage, chosen['folder'])
|
| 199 |
+
binary = tifffile.imread(storage.checked(folder / 'forward.components.tif', 'submissions')).astype(bool)
|
| 200 |
+
outlined = overlay(ct, rows, binary, [s for s, _ in states])
|
| 201 |
+
errors = None
|
| 202 |
+
if (folder / 'forward.components.errors.png').is_file():
|
| 203 |
+
errors = np.asarray(Image.open(storage.checked(folder / 'forward.components.errors.png', 'submissions')))
|
| 204 |
+
zoom = None
|
| 205 |
+
if linked:
|
| 206 |
+
marks = [{'surface_yx': r['surface_yx'], 'id': r['id'], 'state': s} for r, (s, _) in list(zip(rows, states))[:60]]
|
| 207 |
+
zoom = roi_figure(mesh, chosen['origin_yx'], scores, marks, title='ROI y,x ' + str(chosen['origin_yx']) + ' · vue face à la surface')
|
| 208 |
+
table = [[r['id'], s, ' ; '.join(why), r['area_um2'], r['major_um'], r['elongation'], r['orientation_deg'], r['mean_score'],
|
| 209 |
+
round(100 * r['reverse_support'], 1), r['asymmetry'], r['depth_spread_mean'],
|
| 210 |
+
'—' if r['mesh_stretch_yx'] is None else f'{r["mesh_stretch_yx"][0]:.2f} · {r["mesh_stretch_yx"][1]:.2f}',
|
| 211 |
+
TRUTH.get(r.get('truth'), '—')] for r, (s, why) in list(zip(rows, states))[:MAX_ROWS]]
|
| 212 |
+
kept = sum(s == 'retenu' for s, _ in states)
|
| 213 |
+
role = ROLES.get(report.get('labels_role'), report.get('labels_role'))
|
| 214 |
+
transfer = (report.get('surface') or {}).get('label_transfer') or {}
|
| 215 |
+
note = ('### Dossier · ' + html.escape(item['label']) + ' · ROI y,x ' + str(chosen['origin_yx']) + ' \n'
|
| 216 |
+
f'Moteur du masque : **{report.get("selected_engine")}** · seuil brut 0,5 · composantes ≥ 8 px · '
|
| 217 |
+
f'**{summary["components"]} composante(s)**, {100 * summary["ink_fraction"]:.2f} % de la ROI. \n'
|
| 218 |
+
+ ('Tri : **' + str(kept) + ' retenue(s)**, ' + str(len(states) - kept) + ' écartée(s) · portes figées le '
|
| 219 |
+
+ time.strftime('%Y-%m-%d', time.gmtime(gates['created_at'])) + ' sur ' + html.escape(str(gates['source'])) + '. \n'
|
| 220 |
+
if gates else 'Tri : **non étalonné** — les mesures sont affichées sans verdict. \n')
|
| 221 |
+
+ 'Orientation dominante des traits allongés : **' + str(summary.get('dominant_orientation_deg', '—')) + ' °** (cohérence '
|
| 222 |
+
+ str(summary.get('orientation_coherence', '—')) + ') · espacement médian entre composantes voisines : **'
|
| 223 |
+
+ str(summary.get('nearest_neighbour_spacing_um', '—')) + ' µm** · périodicité des lignes : **'
|
| 224 |
+
+ str(summary.get('row_period_um', '—')) + ' µm** (force ' + str(summary.get('row_period_strength', '—')) + '). \n'
|
| 225 |
+
'Annotations : **' + html.escape(str(role)) + '**'
|
| 226 |
+
+ (f' · transfert 3D p95 {transfer["residual_p95_um"]:.2f} µm, {100 * transfer["mapped_fraction"]:.1f} % des pixels' if transfer.get('residual_p95_um') is not None else '')
|
| 227 |
+
+ (' · ' + html.escape(transfer['refused']) if transfer.get('refused') else '') + '. \n'
|
| 228 |
+
'**Transcription : — (vide, en attente d’une lecture humaine qualifiée et signée).** '
|
| 229 |
+
'« Retenu » décrit une forme stable et géométriquement cohérente, pas la présence d’encre ni un caractère.')
|
| 230 |
+
return zoom, ct, (scores * 255).astype('uint8'), outlined, errors, table, note
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def calibrate_gates(storage, case='pherc0841-w00', stream=None):
|
| 234 |
+
"""Étalonne une seule fois les portes de tri sur les composantes annotées de la surface indépendante."""
|
| 235 |
+
from .candidates import calibrate, measure
|
| 236 |
+
from .vc3d_bridge import grid_matches_surface
|
| 237 |
+
item, mesh, shape = _context(storage, case, stream)
|
| 238 |
+
linked = shape is not None and grid_matches_surface(mesh, shape)
|
| 239 |
+
rows = []; used = 0
|
| 240 |
+
for region in analysed_rois(storage, case):
|
| 241 |
+
folder = storage.checked(storage.folder('submissions') / region['folder'], 'submissions')
|
| 242 |
+
report = json.loads(storage.checked(folder / 'metadata.json', 'submissions').read_text(encoding='utf-8'))
|
| 243 |
+
if report.get('labels_role') != 'independent_public_annotation':
|
| 244 |
+
continue
|
| 245 |
+
rows += measure(storage, folder, mesh if linked else None, report)[0]; used += 1
|
| 246 |
+
gates = calibrate(storage, rows, case + ' · ' + str(used) + ' ROI annotée(s)')
|
| 247 |
+
lines = ['Portes ' + ('**déjà figées** (inchangées)' if gates['frozen'] else '**étalonnées et figées**') + ' sur '
|
| 248 |
+
+ html.escape(str(gates['source'])) + f' : {gates["ink_components"]} composantes « encre », {gates["no_ink_components"]} « sans encre ».']
|
| 249 |
+
for name, gate in gates['features'].items():
|
| 250 |
+
lines.append(f'- `{name}` : AUC {gate["auc"]} · ' + (('porte : ' + ('≥ ' if gate['direction'] == 'min' else '≤ ') + format(gate['threshold'], 'g'))
|
| 251 |
+
if gate['used_as_gate'] else 'non utilisée (séparation insuffisante)'))
|
| 252 |
+
lines.append('Seuils choisis sur ces mêmes composantes : leur réussite sur cette surface est optimiste.')
|
| 253 |
+
return ' \n'.join(lines)
|
| 254 |
|
| 255 |
|
| 256 |
def build_production(controller, authorized, secret):
|
|
|
|
| 283 |
loop_stop = gr.Button('Arrêter la boucle')
|
| 284 |
loop_reload = gr.Button('Recharger le dernier résumé')
|
| 285 |
loop_status = gr.Markdown('Aucune boucle lancée dans cette session.')
|
| 286 |
+
loop_table = gr.Dataframe(headers=LOOP_HEADERS, row_count=0, interactive=False, wrap=True,
|
| 287 |
label='Une ligne par ROI · seuil brut 0,5 · composantes ≥ 8 px')
|
| 288 |
loop_download = gr.HTML()
|
| 289 |
+
gr.Markdown('#### 3 · Maillage 3D réel et repère plat')
|
| 290 |
with gr.Row():
|
| 291 |
+
mesh_case = gr.Dropdown(choices, value=choices[-1][1], label='Surface')
|
| 292 |
+
mesh_roi = gr.Dropdown([('Aucune ROI ouverte', '')], value='', label='ROI analysée · se remplit au chargement du maillage')
|
| 293 |
+
with gr.Row():
|
| 294 |
+
mesh_button = gr.Button('Charger le maillage 3D')
|
| 295 |
+
dossier_button = gr.Button('Ouvrir le dossier de la ROI', variant='primary')
|
| 296 |
+
calibrate_button = gr.Button('Étalonner les portes de tri (une seule fois)')
|
| 297 |
+
with gr.Row():
|
| 298 |
+
mesh_plot = gr.Plot(label='Vue d’ensemble · repère 3D du volume CT')
|
| 299 |
+
mesh_locator = gr.Plot(label='Plan de situation · repère plat de la surface')
|
| 300 |
mesh_note = gr.Markdown('Le maillage se charge à la demande.')
|
| 301 |
+
gr.Markdown('#### 4 · Dossier technique de la ROI')
|
| 302 |
+
dossier_note = gr.Markdown('Choisir une ROI analysée puis **Ouvrir le dossier de la ROI**.')
|
| 303 |
+
dossier_zoom = gr.Plot(label='Vue rapprochée · scores plaqués sur le relief réel, caméra face à la surface')
|
| 304 |
with gr.Row():
|
| 305 |
+
dossier_ct = gr.Image(label='CT · plan central', type='numpy', interactive=False, height=300, format='png')
|
| 306 |
+
dossier_score = gr.Image(label='Scores directs', type='numpy', interactive=False, height=300, format='png')
|
| 307 |
+
dossier_outline = gr.Image(label='Composantes · vert retenu, rouge écarté, ambre non étalonné', type='numpy', interactive=False, height=300, format='png')
|
| 308 |
+
dossier_errors = gr.Image(label='Écarts aux annotations · vert VP, rouge FP, bleu FN', type='numpy', interactive=False, height=300, format='png')
|
| 309 |
+
dossier_table = gr.Dataframe(headers=COMPONENT_HEADERS, row_count=0, interactive=False, wrap=True,
|
| 310 |
+
label='Composantes mesurées · de la plus grande à la plus petite')
|
| 311 |
+
calibrate_note = gr.Markdown('')
|
| 312 |
|
| 313 |
def view(report, folder, prefix=''):
|
| 314 |
link = ''
|
|
|
|
| 319 |
link = '<a class="download-result" href="/gradio/vesuvius-download/' + name + '" download="' + name + '">Télécharger le résumé de la boucle (JSON + CSV)</a>'
|
| 320 |
except (ValueError, OSError):
|
| 321 |
pass
|
| 322 |
+
refused = sum(bool(r.get('fallback')) for r in report['rows'])
|
| 323 |
text = (prefix + f'**{report["rois_done"]} ROI terminée(s) sur {report["rois_requested"]}**, {report["rois_failed"]} en échec · '
|
| 324 |
'rouleaux : ' + (', '.join(report['scrolls']) or 'aucun') + f' · {report["seconds"]:.0f} s. \n'
|
| 325 |
+
+ (f'**W8 refusé par la qualification sur {refused} ROI** : le masque vient alors de la référence flottante. \n' if refused else '')
|
| 326 |
+
+ 'PHerc0139 annoté : métriques **internes à l’entraînement**. PHerc0841 w00 : annotations publiques **indépendantes**, '
|
| 327 |
+
'transférées par la géométrie 3D. Sans annotation, aucune justesse n’est mesurée.')
|
| 328 |
return text, loop_rows(report['rows']), link
|
| 329 |
|
| 330 |
def probe(key, request: gr.Request):
|
|
|
|
| 377 |
def load_mesh(key, case, roi, request: gr.Request):
|
| 378 |
guard(key, request)
|
| 379 |
try:
|
| 380 |
+
fig, locator, note, regions = mesh_view(storage, case, roi or None)
|
| 381 |
+
except (ValueError, OSError) as exc:
|
| 382 |
+
return None, None, 'Maillage indisponible : ' + html.escape(type(exc).__name__ + ': ' + str(exc)[:300]), gr.skip()
|
| 383 |
+
options = [('Aucune ROI ouverte', '')] + [(str(n) + ' · ' + r['label'], r['folder']) for n, r in enumerate(regions[:MAX_ROWS], 1)]
|
| 384 |
+
return fig, locator, note, gr.update(choices=options, value=roi if any(roi == v for _, v in options) else '')
|
| 385 |
+
|
| 386 |
+
def open_dossier(key, case, roi, request: gr.Request):
|
| 387 |
+
guard(key, request)
|
| 388 |
+
try:
|
| 389 |
+
zoom, ct, score, outlined, errors, table, note = dossier_view(storage, case, roi)
|
| 390 |
+
fig, locator, _, _ = mesh_view(storage, case, roi)
|
| 391 |
+
except (ValueError, OSError, KeyError) as exc:
|
| 392 |
+
return (None, None, None, None, None, [], 'Dossier indisponible : ' + html.escape(type(exc).__name__ + ': ' + str(exc)[:300]),
|
| 393 |
+
gr.skip(), gr.skip())
|
| 394 |
+
return zoom, ct, score, outlined, errors, table, note, fig, locator
|
| 395 |
+
|
| 396 |
+
def run_calibration(key, request: gr.Request):
|
| 397 |
+
guard(key, request)
|
| 398 |
+
try:
|
| 399 |
+
return calibrate_gates(storage)
|
| 400 |
except (ValueError, OSError) as exc:
|
| 401 |
+
return '**Étalonnage impossible :** ' + html.escape(str(exc)[:400])
|
|
|
|
|
|
|
| 402 |
|
| 403 |
probe_button.click(probe, [secret], [probe_table], concurrency_limit=1, **private_event())
|
| 404 |
loop_button.click(launch, [secret, loop_cases, loop_tiles, loop_radius, loop_device],
|
| 405 |
[loop_status, loop_table, loop_download], concurrency_limit=None, **private_event())
|
| 406 |
loop_stop.click(stop, [secret], [loop_status], queue=False, **private_event())
|
| 407 |
loop_reload.click(reload, [secret], [loop_status, loop_table, loop_download], queue=False, **private_event())
|
| 408 |
+
mesh_button.click(load_mesh, [secret, mesh_case, mesh_roi], [mesh_plot, mesh_locator, mesh_note, mesh_roi],
|
| 409 |
concurrency_limit=1, **private_event())
|
| 410 |
+
dossier_button.click(open_dossier, [secret, mesh_case, mesh_roi],
|
| 411 |
+
[dossier_zoom, dossier_ct, dossier_score, dossier_outline, dossier_errors, dossier_table, dossier_note,
|
| 412 |
+
mesh_plot, mesh_locator], concurrency_limit=1, **private_event())
|
| 413 |
+
calibrate_button.click(run_calibration, [secret], [calibrate_note], concurrency_limit=1, **private_event())
|
src/surface_manifest.py
CHANGED
|
@@ -14,7 +14,7 @@ from pathlib import Path
|
|
| 14 |
MANIFEST = Path(__file__).resolve().parent.parent / 'config/surface-manifest-v1.json'
|
| 15 |
SIZE = 512
|
| 16 |
MAX_TILES = 8
|
| 17 |
-
PLAN_RULE = 'surface-plan/1'
|
| 18 |
|
| 19 |
|
| 20 |
def catalog():
|
|
@@ -41,7 +41,7 @@ def source_uri(item):
|
|
| 41 |
|
| 42 |
def label_uris(item):
|
| 43 |
labels = item.get('labels')
|
| 44 |
-
if not labels:
|
| 45 |
return None
|
| 46 |
base = catalog()['label_root'] + labels['family'] + '/' + labels['segment'] + '/' + labels['segment']
|
| 47 |
return {'labels': base + '_inklabels.zarr', 'supervision': base + '_supervision_mask.zarr'}
|
|
@@ -115,8 +115,17 @@ def read_input(storage, case, origin=None, cancelled=lambda: False, stream=None)
|
|
| 115 |
evidence = [{'role': 'ct', 'uri': info['request']['uri'], 'sha256': info['sha256'],
|
| 116 |
'network_bytes': info['network_bytes'], 'chunks_touched': info['chunks_touched'],
|
| 117 |
'chunks_absent': info['chunks_absent'], 'from_cache': info['from_cache']}]
|
| 118 |
-
labels = mask = training = None; role = 'no_annotation'
|
| 119 |
-
if item.get('labels') and not cancelled():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
pair, detail = read_labels(stream, item, origin, contract['shape'])
|
| 121 |
role = detail['labels_role']
|
| 122 |
if pair is not None:
|
|
@@ -129,7 +138,7 @@ def read_input(storage, case, origin=None, cancelled=lambda: False, stream=None)
|
|
| 129 |
'scale_source': 'NGFF' if contract['scale_verified'] else 'manifeste (nom du volume), non déclarée par le Zarr',
|
| 130 |
'anatomical_alignment_certified': False},
|
| 131 |
'surface': {'case': case, 'scroll': item['scroll'], 'surface_shape_zyx': contract['shape'],
|
| 132 |
-
'source_chunks': contract['chunks'], 'streamed': True}}
|
| 133 |
|
| 134 |
|
| 135 |
def locator(report, surface):
|
|
@@ -198,6 +207,43 @@ def _plan_from_mesh(storage, stream, item, shape):
|
|
| 198 |
'mesh_sha256': mesh['sha256']}
|
| 199 |
|
| 200 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
def plan(storage, case, tiles, stream=None):
|
| 202 |
"""Origines gelées d'une surface : calculées une fois, relues ensuite à l'identique."""
|
| 203 |
from .hub_stream import Stream
|
|
@@ -218,6 +264,13 @@ def plan(storage, case, tiles, stream=None):
|
|
| 218 |
fixed = [checked_origin(list(o), shape) for o in (item.get('origins_yx') or [])]
|
| 219 |
if len(fixed) >= MAX_TILES:
|
| 220 |
ranked, detail = [], {'rule': 'origines fixées dans le manifeste'}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
elif item.get('labels'):
|
| 222 |
ranked, detail = _plan_from_labels(stream, item, shape)
|
| 223 |
else:
|
|
|
|
| 14 |
MANIFEST = Path(__file__).resolve().parent.parent / 'config/surface-manifest-v1.json'
|
| 15 |
SIZE = 512
|
| 16 |
MAX_TILES = 8
|
| 17 |
+
PLAN_RULE = 'surface-plan/1' # l'identité d'un plan inclut l'entrée du manifeste : la changer recalcule le plan
|
| 18 |
|
| 19 |
|
| 20 |
def catalog():
|
|
|
|
| 41 |
|
| 42 |
def label_uris(item):
|
| 43 |
labels = item.get('labels')
|
| 44 |
+
if not labels or labels.get('kind') == 'mesh_transfer':
|
| 45 |
return None
|
| 46 |
base = catalog()['label_root'] + labels['family'] + '/' + labels['segment'] + '/' + labels['segment']
|
| 47 |
return {'labels': base + '_inklabels.zarr', 'supervision': base + '_supervision_mask.zarr'}
|
|
|
|
| 115 |
evidence = [{'role': 'ct', 'uri': info['request']['uri'], 'sha256': info['sha256'],
|
| 116 |
'network_bytes': info['network_bytes'], 'chunks_touched': info['chunks_touched'],
|
| 117 |
'chunks_absent': info['chunks_absent'], 'from_cache': info['from_cache']}]
|
| 118 |
+
labels = mask = training = None; role = 'no_annotation'; transfer_report = None
|
| 119 |
+
if (item.get('labels') or {}).get('kind') == 'mesh_transfer' and not cancelled():
|
| 120 |
+
# v4.23.0 : annotations d'une autre grille, rendues seulement si les portes géométriques 3D passent.
|
| 121 |
+
from .label_transfer import transfer, TransferRefused
|
| 122 |
+
try:
|
| 123 |
+
labels, mask, detail = transfer(storage, stream, item, origin)
|
| 124 |
+
training = np.zeros_like(mask); evidence += detail['evidence']
|
| 125 |
+
role = 'independent_public_annotation'; transfer_report = detail['gate']
|
| 126 |
+
except TransferRefused as exc:
|
| 127 |
+
role = 'label_transfer_refused'; transfer_report = {'refused': str(exc)[:400]}
|
| 128 |
+
elif item.get('labels') and not cancelled():
|
| 129 |
pair, detail = read_labels(stream, item, origin, contract['shape'])
|
| 130 |
role = detail['labels_role']
|
| 131 |
if pair is not None:
|
|
|
|
| 138 |
'scale_source': 'NGFF' if contract['scale_verified'] else 'manifeste (nom du volume), non déclarée par le Zarr',
|
| 139 |
'anatomical_alignment_certified': False},
|
| 140 |
'surface': {'case': case, 'scroll': item['scroll'], 'surface_shape_zyx': contract['shape'],
|
| 141 |
+
'source_chunks': contract['chunks'], 'streamed': True, 'label_transfer': transfer_report}}
|
| 142 |
|
| 143 |
|
| 144 |
def locator(report, surface):
|
|
|
|
| 207 |
'mesh_sha256': mesh['sha256']}
|
| 208 |
|
| 209 |
|
| 210 |
+
def _plan_from_transfer(storage, stream, item, shape):
|
| 211 |
+
"""Tuiles classées par couverture des annotations publiques, vues à travers le transfert 3D (pyramide grossière)."""
|
| 212 |
+
import numpy as np
|
| 213 |
+
from .label_transfer import build
|
| 214 |
+
spec = item['labels']; mapping = build(storage, stream, item)
|
| 215 |
+
level = '5'; coarse = {}
|
| 216 |
+
for role in ('labels', 'supervision', 'validation'):
|
| 217 |
+
if spec.get(role):
|
| 218 |
+
uri = spec['root'] + '/' + spec[role]
|
| 219 |
+
meta = stream.probe(uri, levels=(level,))['levels'][0]
|
| 220 |
+
if not meta['scale_zyx'] or meta['scale_zyx'][1] != meta['scale_zyx'][2]:
|
| 221 |
+
raise ValueError('pyramide des annotations sans échelle déclarée')
|
| 222 |
+
data, _ = stream.window(uri, level, [0, 0, 0], meta['shape'])
|
| 223 |
+
coarse[role] = (data.max(0) > 0, meta['scale_zyx'][1])
|
| 224 |
+
annotated = np.zeros_like(coarse['labels'][0])
|
| 225 |
+
for role in ('supervision', 'validation'):
|
| 226 |
+
if role in coarse:
|
| 227 |
+
annotated |= coarse[role][0]
|
| 228 |
+
factor = coarse['labels'][1]; offsets = (np.arange(6) + .5) * SIZE / 6
|
| 229 |
+
ranked = []
|
| 230 |
+
for y, x in _tiles(shape[1], shape[2]):
|
| 231 |
+
points = np.stack(np.meshgrid(y + offsets, x + offsets, indexing='ij'), -1).reshape(-1, 2)
|
| 232 |
+
canvas, _, good = mapping.project(points)
|
| 233 |
+
if good.mean() < .9:
|
| 234 |
+
continue
|
| 235 |
+
index = np.floor(canvas[good] / factor).astype(int)
|
| 236 |
+
index = index[(index >= 0).all(1) & (index[:, 0] < annotated.shape[0]) & (index[:, 1] < annotated.shape[1])]
|
| 237 |
+
if not len(index):
|
| 238 |
+
continue
|
| 239 |
+
covered = float(annotated[index[:, 0], index[:, 1]].mean())
|
| 240 |
+
if covered > 0:
|
| 241 |
+
ink = bool((coarse['labels'][0] & annotated)[index[:, 0], index[:, 1]].any())
|
| 242 |
+
ranked.append((0 if ink else 1, -round(covered, 6), y, x))
|
| 243 |
+
return [[y, x] for _, _, y, x in sorted(ranked)], {'rule': 'annotations publiques vues par transfert 3D, niveau ' + level + ' ; encre annotée présente d’abord, puis fraction annotée décroissante, puis y,x',
|
| 244 |
+
'transfer': mapping.identity}
|
| 245 |
+
|
| 246 |
+
|
| 247 |
def plan(storage, case, tiles, stream=None):
|
| 248 |
"""Origines gelées d'une surface : calculées une fois, relues ensuite à l'identique."""
|
| 249 |
from .hub_stream import Stream
|
|
|
|
| 264 |
fixed = [checked_origin(list(o), shape) for o in (item.get('origins_yx') or [])]
|
| 265 |
if len(fixed) >= MAX_TILES:
|
| 266 |
ranked, detail = [], {'rule': 'origines fixées dans le manifeste'}
|
| 267 |
+
elif (item.get('labels') or {}).get('kind') == 'mesh_transfer':
|
| 268 |
+
try:
|
| 269 |
+
ranked, detail = _plan_from_transfer(storage, stream, item, shape)
|
| 270 |
+
except (ValueError, OSError) as exc:
|
| 271 |
+
# Porte géométrique refusée : la surface reste traitable sans annotation, par la validité du maillage.
|
| 272 |
+
ranked, detail = _plan_from_mesh(storage, stream, item, shape)
|
| 273 |
+
detail['rule'] += ' ; transfert des annotations refusé : ' + str(exc)[:200]
|
| 274 |
elif item.get('labels'):
|
| 275 |
ranked, detail = _plan_from_labels(stream, item, shape)
|
| 276 |
else:
|
src/unified_pipeline.py
CHANGED
|
@@ -13,7 +13,7 @@ CASES = ('reference-w016', 'published-w043')
|
|
| 13 |
DEPTH_RADII = (0, 1, 2)
|
| 14 |
QUANTIZATIONS = ('auto8', 'experimental4', 'reference')
|
| 15 |
# FIX(AUDIT): version relevée ; les rapports portent de nouveaux champs (moteur, provenance, comparabilité).
|
| 16 |
-
VERSION = '4.
|
| 17 |
# FIX(AUDIT): provenance d'entraînement de ink_9um consignée par source ; jamais déduite de l'absence d'annotations.
|
| 18 |
TRAINING_PROVENANCE = {
|
| 19 |
'reference-w016': {'scroll':'PHerc0139', 'status':'seen_roll', 'segment_status':'used_in_checkpoint_development',
|
|
@@ -345,7 +345,11 @@ def run(storage, case='reference-w016', radius=2, quantization='auto8', device='
|
|
| 345 |
'metrics':metrics,'reference_metrics':reference_metrics,'quantized_candidate_metrics':candidate_metrics,
|
| 346 |
'threshold_free_metrics':threshold_free_metrics,'engine_comparison':engine_gap,
|
| 347 |
'metrics_scope':('no ground truth; no detection metrics computed' if labels is None else 'fixed public online-validation mask' if legacy
|
|
|
|
|
|
|
| 348 |
else 'in-sample: public training supervision mask of this ROI; not a validation measure'),
|
|
|
|
|
|
|
| 349 |
'display_checks':checks,'display_transform':'clip((p-0.25)/0.5,0,1); raw TIFF unchanged; unobserved pixels NaN',
|
| 350 |
'formal_checks':proofs,'unit_tests':contracts,'cache_objects_quarantined':repaired,
|
| 351 |
'windows_reused':reused,
|
|
|
|
| 13 |
DEPTH_RADII = (0, 1, 2)
|
| 14 |
QUANTIZATIONS = ('auto8', 'experimental4', 'reference')
|
| 15 |
# FIX(AUDIT): version relevée ; les rapports portent de nouveaux champs (moteur, provenance, comparabilité).
|
| 16 |
+
VERSION = '4.23.0'
|
| 17 |
# FIX(AUDIT): provenance d'entraînement de ink_9um consignée par source ; jamais déduite de l'absence d'annotations.
|
| 18 |
TRAINING_PROVENANCE = {
|
| 19 |
'reference-w016': {'scroll':'PHerc0139', 'status':'seen_roll', 'segment_status':'used_in_checkpoint_development',
|
|
|
|
| 345 |
'metrics':metrics,'reference_metrics':reference_metrics,'quantized_candidate_metrics':candidate_metrics,
|
| 346 |
'threshold_free_metrics':threshold_free_metrics,'engine_comparison':engine_gap,
|
| 347 |
'metrics_scope':('no ground truth; no detection metrics computed' if labels is None else 'fixed public online-validation mask' if legacy
|
| 348 |
+
else 'independent roll: public annotations of a roll absent from the model card, transferred through gated 3D mesh correspondence; one ROI, not certified'
|
| 349 |
+
if labels_role=='independent_public_annotation'
|
| 350 |
else 'in-sample: public training supervision mask of this ROI; not a validation measure'),
|
| 351 |
+
# v4.23.0 : vrai seulement pour des annotations publiques d'un rouleau absent de la fiche du modèle.
|
| 352 |
+
'independent_roll_evaluated':labels is not None and labels_role=='independent_public_annotation',
|
| 353 |
'display_checks':checks,'display_transform':'clip((p-0.25)/0.5,0,1); raw TIFF unchanged; unobserved pixels NaN',
|
| 354 |
'formal_checks':proofs,'unit_tests':contracts,'cache_objects_quarantined':repaired,
|
| 355 |
'windows_reused':reused,
|
src/vc3d_bridge.py
CHANGED
|
@@ -33,10 +33,14 @@ def mesh_uri(stream, item):
|
|
| 33 |
|
| 34 |
|
| 35 |
def load_tifxyz(storage, stream, item):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
"""Grille (H,W,3) en voxels du volume CT, masque de validité, échelle et empreinte."""
|
| 37 |
import numpy as np
|
| 38 |
import tifffile
|
| 39 |
-
uri = mesh_uri(stream, item)
|
| 40 |
meta_bytes, _ = stream.small_file(uri + '/meta.json', 64 * 1024)
|
| 41 |
meta = json.loads(meta_bytes.decode('utf-8'))
|
| 42 |
scale = meta.get('scale')
|
|
@@ -58,7 +62,7 @@ def load_tifxyz(storage, stream, item):
|
|
| 58 |
valid = np.isfinite(xyz).all(-1) & ~(xyz <= -1).all(-1) & (xyz >= 0).all(-1)
|
| 59 |
# meta.scale = [échelle x, échelle y] : cellules de grille par pixel de surface.
|
| 60 |
return {'uri': uri, 'xyz': xyz, 'valid': valid, 'scale_yx': [float(scale[1]), float(scale[0])],
|
| 61 |
-
'voxel_um': float(
|
| 62 |
'grid_shape': [int(v) for v in valid.shape], 'valid_fraction': float(valid.mean())}
|
| 63 |
|
| 64 |
|
|
@@ -107,47 +111,184 @@ def roi_patch(mesh, origin_yx, size=512, samples=PATCH_SAMPLES):
|
|
| 107 |
return np.round(points * mesh['voxel_um'] / 1000, 3)
|
| 108 |
|
| 109 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
def figure(mesh, surface_shape_yx=None, regions=(), overlay=None, title=''):
|
| 111 |
-
"""
|
| 112 |
|
| 113 |
regions : [{'origin_yx':[y,x], 'label':str}] ; overlay : {'origin_yx':[y,x], 'scores':(512,512) dans [0,1]}.
|
|
|
|
| 114 |
"""
|
| 115 |
import numpy as np
|
| 116 |
import plotly.graph_objects as go
|
| 117 |
small = decimated(mesh)
|
| 118 |
v, f = small['vertices_mm'], small['faces']
|
|
|
|
|
|
|
| 119 |
fig = go.Figure()
|
| 120 |
if len(f):
|
| 121 |
fig.add_trace(go.Mesh3d(x=v[:, 0], y=v[:, 1], z=v[:, 2], i=f[:, 0], j=f[:, 1], k=f[:, 2],
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
lighting={'
|
| 125 |
-
|
| 126 |
-
placed = skipped = 0
|
| 127 |
if linked:
|
| 128 |
-
for region in list(regions)[:64]:
|
| 129 |
patch = roi_patch(mesh, region['origin_yx'], samples=9)
|
| 130 |
if patch is None:
|
| 131 |
skipped += 1; continue
|
| 132 |
-
|
|
|
|
| 133 |
fig.add_trace(go.Scatter3d(x=edge[:, 0], y=edge[:, 1], z=edge[:, 2], mode='lines',
|
| 134 |
-
line={'color': '#
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
scores = np.asarray(overlay['scores'], dtype='float32')
|
| 140 |
if patch is not None and scores.shape == (512, 512):
|
| 141 |
step = np.linspace(0, 511, PATCH_SAMPLES).round().astype(int)
|
| 142 |
fig.add_trace(go.Surface(x=patch[..., 0], y=patch[..., 1], z=patch[..., 2],
|
| 143 |
surfacecolor=scores[np.ix_(step, step)], cmin=0, cmax=1, colorscale='Inferno',
|
| 144 |
-
colorbar={'title': '
|
|
|
|
| 145 |
hovertemplate='score affiché=%{surfacecolor:.2f}<extra></extra>'))
|
| 146 |
-
fig.update_layout(title={'text': title, 'font': {'size': 16}}, height=
|
| 147 |
-
scene={'
|
| 148 |
-
'zaxis': {'title': 'z volume (mm)'}}, legend={'orientation': 'h', 'y': 0})
|
| 149 |
summary = {'vertices_sent': int(len(v)), 'faces_sent': int(len(f)), 'stride': small['stride'],
|
| 150 |
'grid_shape': mesh['grid_shape'], 'valid_fraction': mesh['valid_fraction'],
|
| 151 |
'flat_to_3d_link': 'grille tifxyz vérifiée' if linked else 'non établi : dimensions de grille et de surface non concordantes ou surface non sondée',
|
| 152 |
-
'regions_placed': placed, 'regions_outside_mesh': skipped, '
|
|
|
|
| 153 |
return fig, summary
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
|
| 35 |
def load_tifxyz(storage, stream, item):
|
| 36 |
+
"""Maillage du segment rendu sur le volume de la surface (résolu par règle)."""
|
| 37 |
+
return load_tifxyz_uri(storage, stream, mesh_uri(stream, item), float(item['voxel_um']))
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def load_tifxyz_uri(storage, stream, uri, voxel_um):
|
| 41 |
"""Grille (H,W,3) en voxels du volume CT, masque de validité, échelle et empreinte."""
|
| 42 |
import numpy as np
|
| 43 |
import tifffile
|
|
|
|
| 44 |
meta_bytes, _ = stream.small_file(uri + '/meta.json', 64 * 1024)
|
| 45 |
meta = json.loads(meta_bytes.decode('utf-8'))
|
| 46 |
scale = meta.get('scale')
|
|
|
|
| 62 |
valid = np.isfinite(xyz).all(-1) & ~(xyz <= -1).all(-1) & (xyz >= 0).all(-1)
|
| 63 |
# meta.scale = [échelle x, échelle y] : cellules de grille par pixel de surface.
|
| 64 |
return {'uri': uri, 'xyz': xyz, 'valid': valid, 'scale_yx': [float(scale[1]), float(scale[0])],
|
| 65 |
+
'voxel_um': float(voxel_um), 'sha256': digest.hexdigest(),
|
| 66 |
'grid_shape': [int(v) for v in valid.shape], 'valid_fraction': float(valid.mean())}
|
| 67 |
|
| 68 |
|
|
|
|
| 111 |
return np.round(points * mesh['voxel_um'] / 1000, 3)
|
| 112 |
|
| 113 |
|
| 114 |
+
def interpolate(mesh, points_yx):
|
| 115 |
+
"""Points 3D (voxels) de positions y,x du repère plat ; ok=False si une maille voisine est incomplète."""
|
| 116 |
+
import numpy as np
|
| 117 |
+
xyz, valid = mesh['xyz'], mesh['valid']; sy, sx = mesh['scale_yx']
|
| 118 |
+
gy = np.asarray(points_yx[:, 0], dtype='float64') * sy; gx = np.asarray(points_yx[:, 1], dtype='float64') * sx
|
| 119 |
+
inside = (gy >= 0) & (gx >= 0) & (gy <= valid.shape[0] - 1) & (gx <= valid.shape[1] - 1)
|
| 120 |
+
y0 = np.clip(np.floor(gy).astype(int), 0, valid.shape[0] - 2); x0 = np.clip(np.floor(gx).astype(int), 0, valid.shape[1] - 2)
|
| 121 |
+
ok = inside & valid[y0, x0] & valid[y0, x0 + 1] & valid[y0 + 1, x0] & valid[y0 + 1, x0 + 1]
|
| 122 |
+
fy = (gy - y0)[:, None]; fx = (gx - x0)[:, None]
|
| 123 |
+
points = (xyz[y0, x0] * (1 - fy) * (1 - fx) + xyz[y0, x0 + 1] * (1 - fy) * fx
|
| 124 |
+
+ xyz[y0 + 1, x0] * fy * (1 - fx) + xyz[y0 + 1, x0 + 1] * fy * fx)
|
| 125 |
+
return points.astype('float64'), ok
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def local_stretch(mesh, y, x, step=20.0):
|
| 129 |
+
"""Longueur 3D parcourue par pixel plat autour de (y,x), en pixels nominaux : 1,0 = aucune déformation.
|
| 130 |
+
|
| 131 |
+
Renvoie (étirement en y, étirement en x) ou None si le voisinage du maillage est incomplet.
|
| 132 |
+
"""
|
| 133 |
+
import numpy as np
|
| 134 |
+
probes = np.array([[y - step, x], [y + step, x], [y, x - step], [y, x + step]], dtype='float64')
|
| 135 |
+
points, ok = interpolate(mesh, probes)
|
| 136 |
+
if not ok.all():
|
| 137 |
+
return None
|
| 138 |
+
return (float(np.linalg.norm(points[1] - points[0]) / (2 * step)), float(np.linalg.norm(points[3] - points[2]) / (2 * step)))
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
DARK = {'paper_bgcolor': '#0b1220', 'font': {'color': '#e2e8f0'}}
|
| 142 |
+
AXIS = {'backgroundcolor': '#0b1220', 'gridcolor': '#334155', 'zerolinecolor': '#334155', 'color': '#cbd5e1'}
|
| 143 |
+
MESH_LIGHT = {'ambient': .42, 'diffuse': .95, 'specular': .08, 'roughness': .7, 'fresnel': .05}
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def _scene(units='mm'):
|
| 147 |
+
return {'aspectmode': 'data', 'bgcolor': '#0b1220',
|
| 148 |
+
'xaxis': {**AXIS, 'title': 'x volume (' + units + ')'}, 'yaxis': {**AXIS, 'title': 'y volume (' + units + ')'},
|
| 149 |
+
'zaxis': {**AXIS, 'title': 'z volume (' + units + ')'}}
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def _outline(patch):
|
| 153 |
+
import numpy as np
|
| 154 |
+
return np.concatenate([patch[0], patch[1:, -1], patch[-1, -2::-1], patch[-2::-1, 0]])
|
| 155 |
+
|
| 156 |
+
|
| 157 |
def figure(mesh, surface_shape_yx=None, regions=(), overlay=None, title=''):
|
| 158 |
+
"""Vue d'ensemble : maillage réel décimé, ROI numérotées, nappe de scores de la ROI choisie.
|
| 159 |
|
| 160 |
regions : [{'origin_yx':[y,x], 'label':str}] ; overlay : {'origin_yx':[y,x], 'scores':(512,512) dans [0,1]}.
|
| 161 |
+
Les ROI ne sont placées que si la grille du maillage concorde avec la surface rendue.
|
| 162 |
"""
|
| 163 |
import numpy as np
|
| 164 |
import plotly.graph_objects as go
|
| 165 |
small = decimated(mesh)
|
| 166 |
v, f = small['vertices_mm'], small['faces']
|
| 167 |
+
linked = surface_shape_yx is not None and grid_matches_surface(mesh, surface_shape_yx)
|
| 168 |
+
chosen = overlay['origin_yx'] if overlay is not None and linked else None
|
| 169 |
fig = go.Figure()
|
| 170 |
if len(f):
|
| 171 |
fig.add_trace(go.Mesh3d(x=v[:, 0], y=v[:, 1], z=v[:, 2], i=f[:, 0], j=f[:, 1], k=f[:, 2],
|
| 172 |
+
color='#94a3b8', opacity=1.0, flatshading=True, name='Maillage tifxyz', showlegend=True,
|
| 173 |
+
hovertemplate='x=%{x:.2f} mm · y=%{y:.2f} mm · z=%{z:.2f} mm<extra>maillage</extra>',
|
| 174 |
+
lighting=MESH_LIGHT, lightposition={'x': 2000, 'y': -2000, 'z': 3000}))
|
| 175 |
+
placed = skipped = 0; numbered = []
|
|
|
|
| 176 |
if linked:
|
| 177 |
+
for number, region in enumerate(list(regions)[:64], 1):
|
| 178 |
patch = roi_patch(mesh, region['origin_yx'], samples=9)
|
| 179 |
if patch is None:
|
| 180 |
skipped += 1; continue
|
| 181 |
+
selected = chosen is not None and list(region['origin_yx']) == list(chosen)
|
| 182 |
+
edge = _outline(patch)
|
| 183 |
fig.add_trace(go.Scatter3d(x=edge[:, 0], y=edge[:, 1], z=edge[:, 2], mode='lines',
|
| 184 |
+
line={'color': '#38bdf8' if selected else '#fbbf24', 'width': 9 if selected else 5},
|
| 185 |
+
name='ROI ouverte' if selected else 'ROI analysée', legendgroup='sel' if selected else 'roi',
|
| 186 |
+
showlegend=selected or not any(t.legendgroup == 'roi' for t in fig.data),
|
| 187 |
+
text=str(number) + ' · ' + region.get('label', ''), hovertemplate='%{text}<extra></extra>'))
|
| 188 |
+
centre = patch[4, 4]
|
| 189 |
+
fig.add_trace(go.Scatter3d(x=[centre[0]], y=[centre[1]], z=[centre[2]], mode='text', text=[str(number)],
|
| 190 |
+
textfont={'size': 16, 'color': '#38bdf8' if selected else '#fde68a'}, showlegend=False, hoverinfo='skip'))
|
| 191 |
+
numbered.append({'number': number, **region}); placed += 1
|
| 192 |
+
if chosen is not None:
|
| 193 |
+
patch = roi_patch(mesh, chosen)
|
| 194 |
scores = np.asarray(overlay['scores'], dtype='float32')
|
| 195 |
if patch is not None and scores.shape == (512, 512):
|
| 196 |
step = np.linspace(0, 511, PATCH_SAMPLES).round().astype(int)
|
| 197 |
fig.add_trace(go.Surface(x=patch[..., 0], y=patch[..., 1], z=patch[..., 2],
|
| 198 |
surfacecolor=scores[np.ix_(step, step)], cmin=0, cmax=1, colorscale='Inferno',
|
| 199 |
+
colorbar={'title': {'text': 'score affiché'}, 'len': .45, 'x': 1.0, 'tickfont': {'color': '#e2e8f0'}},
|
| 200 |
+
name='Scores de la ROI', lighting={'ambient': 1, 'diffuse': 0, 'specular': 0},
|
| 201 |
hovertemplate='score affiché=%{surfacecolor:.2f}<extra></extra>'))
|
| 202 |
+
fig.update_layout(title={'text': title, 'font': {'size': 16}}, height=620, margin={'t': 50, 'l': 0, 'r': 0, 'b': 0},
|
| 203 |
+
scene=_scene(), legend={'orientation': 'h', 'y': 0, 'font': {'color': '#e2e8f0'}}, uirevision=title, **DARK)
|
|
|
|
| 204 |
summary = {'vertices_sent': int(len(v)), 'faces_sent': int(len(f)), 'stride': small['stride'],
|
| 205 |
'grid_shape': mesh['grid_shape'], 'valid_fraction': mesh['valid_fraction'],
|
| 206 |
'flat_to_3d_link': 'grille tifxyz vérifiée' if linked else 'non établi : dimensions de grille et de surface non concordantes ou surface non sondée',
|
| 207 |
+
'regions_placed': placed, 'regions_outside_mesh': skipped, 'numbered': numbered,
|
| 208 |
+
'mesh_sha256': mesh['sha256'], 'mesh_uri': mesh['uri']}
|
| 209 |
return fig, summary
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def roi_figure(mesh, origin_yx, scores, components=None, margin=256, samples=96, title=''):
|
| 213 |
+
"""Vue rapprochée d'une ROI : relief réel exagéré de rien, scores plaqués, caméra face à la surface.
|
| 214 |
+
|
| 215 |
+
Le voisinage du maillage est montré à pleine résolution de grille ; la nappe porte un point tous les ~5 px.
|
| 216 |
+
components : [{'surface_yx':[y,x], 'id':int, 'state':str}] placés sur la surface par la même grille.
|
| 217 |
+
"""
|
| 218 |
+
import numpy as np
|
| 219 |
+
import plotly.graph_objects as go
|
| 220 |
+
patch = roi_patch(mesh, origin_yx, samples=samples)
|
| 221 |
+
if patch is None:
|
| 222 |
+
return None
|
| 223 |
+
sy, sx = mesh['scale_yx']; valid = mesh['valid']
|
| 224 |
+
r0 = max(0, int((origin_yx[0] - margin) * sy)); r1 = min(valid.shape[0], int(math.ceil((origin_yx[0] + 512 + margin) * sy)) + 1)
|
| 225 |
+
c0 = max(0, int((origin_yx[1] - margin) * sx)); c1 = min(valid.shape[1], int(math.ceil((origin_yx[1] + 512 + margin) * sx)) + 1)
|
| 226 |
+
local = valid[r0:r1, c0:c1].copy()
|
| 227 |
+
# Les mailles couvertes par la nappe sont retirées : deux surfaces confondues scintillent à l'écran.
|
| 228 |
+
rows = np.arange(r0, r1)[:, None] / sy; cols = np.arange(c0, c1)[None, :] / sx
|
| 229 |
+
local &= ~((rows > origin_yx[0]) & (rows < origin_yx[0] + 511) & (cols > origin_yx[1]) & (cols < origin_yx[1] + 511))
|
| 230 |
+
_, faces = triangles(local, 1)
|
| 231 |
+
points = mesh['xyz'][r0:r1, c0:c1].reshape(-1, 3) * mesh['voxel_um'] / 1000
|
| 232 |
+
step = np.linspace(0, 511, samples).round().astype(int)
|
| 233 |
+
colour = np.asarray(scores, 'float32')[np.ix_(step, step)]
|
| 234 |
+
flat = np.stack(np.meshgrid(origin_yx[0] + step, origin_yx[1] + step, indexing='ij'), -1)
|
| 235 |
+
fig = go.Figure()
|
| 236 |
+
if len(faces):
|
| 237 |
+
fig.add_trace(go.Mesh3d(x=points[:, 0], y=points[:, 1], z=points[:, 2], i=faces[:, 0], j=faces[:, 1], k=faces[:, 2],
|
| 238 |
+
color='#64748b', flatshading=True, lighting=MESH_LIGHT, name='Maillage voisin', showlegend=True, hoverinfo='skip'))
|
| 239 |
+
fig.add_trace(go.Surface(x=patch[..., 0], y=patch[..., 1], z=patch[..., 2], surfacecolor=colour, cmin=0, cmax=1,
|
| 240 |
+
colorscale='Inferno', customdata=flat, lighting={'ambient': 1, 'diffuse': 0, 'specular': 0},
|
| 241 |
+
colorbar={'title': {'text': 'score affiché'}, 'len': .6, 'tickfont': {'color': '#e2e8f0'}}, name='Scores',
|
| 242 |
+
hovertemplate='pixel y=%{customdata[0]} · x=%{customdata[1]}<br>score affiché=%{surfacecolor:.2f}<extra></extra>'))
|
| 243 |
+
edge = _outline(patch[::max(1, samples // 8)][:, ::max(1, samples // 8)])
|
| 244 |
+
fig.add_trace(go.Scatter3d(x=edge[:, 0], y=edge[:, 1], z=edge[:, 2], mode='lines', line={'color': '#38bdf8', 'width': 6},
|
| 245 |
+
name='Bord de la ROI', hoverinfo='skip'))
|
| 246 |
+
if components:
|
| 247 |
+
centres = np.array([c['surface_yx'] for c in components], 'float64')
|
| 248 |
+
spots, ok = interpolate(mesh, centres)
|
| 249 |
+
palette = {'retenu': '#34d399', 'écarté': '#f87171', 'non étalonné': '#fbbf24'}
|
| 250 |
+
for state, colour_name in palette.items():
|
| 251 |
+
pick = [i for i, c in enumerate(components) if ok[i] and c['state'] == state]
|
| 252 |
+
if pick:
|
| 253 |
+
p = spots[pick] * mesh['voxel_um'] / 1000
|
| 254 |
+
fig.add_trace(go.Scatter3d(x=p[:, 0], y=p[:, 1], z=p[:, 2], mode='markers+text',
|
| 255 |
+
marker={'size': 4, 'color': colour_name, 'line': {'color': '#0b1220', 'width': 1}},
|
| 256 |
+
text=[str(components[i]['id']) for i in pick], textposition='top center',
|
| 257 |
+
textfont={'size': 11, 'color': colour_name}, name='Composantes · ' + state,
|
| 258 |
+
hovertemplate='composante %{text}<extra>' + state + '</extra>'))
|
| 259 |
+
# Caméra sur la normale moyenne de la nappe, le haut de l'image suivant −y du repère plat.
|
| 260 |
+
ey = patch[-1, samples // 2] - patch[0, samples // 2]; ex = patch[samples // 2, -1] - patch[samples // 2, 0]
|
| 261 |
+
normal = np.cross(ex, ey); length = np.linalg.norm(normal)
|
| 262 |
+
camera = None
|
| 263 |
+
if length > 0:
|
| 264 |
+
normal = normal / length; up = -ey / max(np.linalg.norm(ey), 1e-9)
|
| 265 |
+
# Œil du côté −(x plat × y plat) : x plat va vers la droite et y plat vers le bas, comme sur les images 2D (pas de miroir).
|
| 266 |
+
camera = {'eye': dict(zip('xyz', (-1.6 * normal).tolist())), 'up': dict(zip('xyz', up.tolist()))}
|
| 267 |
+
fig.update_layout(title={'text': title, 'font': {'size': 15}}, height=620, margin={'t': 45, 'l': 0, 'r': 0, 'b': 0},
|
| 268 |
+
scene={**_scene(), **({'camera': camera} if camera else {})}, legend={'orientation': 'h', 'y': 0, 'font': {'color': '#e2e8f0'}},
|
| 269 |
+
uirevision=title, **DARK)
|
| 270 |
+
return fig
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def locator_figure(mesh, surface_shape_yx, regions=(), chosen=None, title=''):
|
| 274 |
+
"""Plan de situation dans le repère plat : zone couverte par le maillage et ROI numérotées."""
|
| 275 |
+
import numpy as np
|
| 276 |
+
import plotly.graph_objects as go
|
| 277 |
+
sy, sx = mesh['scale_yx']; h, w = surface_shape_yx
|
| 278 |
+
fig = go.Figure(go.Heatmap(z=mesh['valid'].astype('uint8'), x0=0, dx=1 / sx, y0=0, dy=1 / sy, zmin=0, zmax=1,
|
| 279 |
+
colorscale=[[0, '#0b1220'], [1, '#475569']], showscale=False, hoverinfo='skip'))
|
| 280 |
+
fig.add_shape(type='rect', x0=0, y0=0, x1=w, y1=h, line={'color': '#94a3b8', 'width': 1, 'dash': 'dot'})
|
| 281 |
+
for number, region in enumerate(list(regions)[:64], 1):
|
| 282 |
+
y, x = region['origin_yx']; selected = chosen is not None and [y, x] == list(chosen)
|
| 283 |
+
colour = '#38bdf8' if selected else '#fbbf24'
|
| 284 |
+
fig.add_trace(go.Scatter(x=[x, x + 512, x + 512, x, x], y=[y, y, y + 512, y + 512, y], mode='lines',
|
| 285 |
+
line={'color': colour, 'width': 3 if selected else 2}, fill='toself',
|
| 286 |
+
fillcolor='rgba(56,189,248,0.25)' if selected else 'rgba(251,191,36,0.18)', showlegend=False,
|
| 287 |
+
text=str(number) + ' · ' + region.get('label', ''), hoveron='fills+points', hovertemplate='%{text}<extra></extra>'))
|
| 288 |
+
fig.add_annotation(x=x + 256, y=y + 256, text='<b>' + str(number) + '</b>', showarrow=False, font={'color': colour, 'size': 14})
|
| 289 |
+
fig.update_xaxes(title='x sur la surface (pixels)', range=[0, w], constrain='domain', gridcolor='#1e293b', color='#cbd5e1', zeroline=False)
|
| 290 |
+
fig.update_yaxes(title='y sur la surface (pixels)', range=[h, 0], scaleanchor='x', scaleratio=1, constrain='domain',
|
| 291 |
+
gridcolor='#1e293b', color='#cbd5e1', zeroline=False)
|
| 292 |
+
fig.update_layout(title={'text': title, 'font': {'size': 15}}, height=620, margin={'t': 45, 'l': 55, 'r': 10, 'b': 45},
|
| 293 |
+
plot_bgcolor='#0b1220', **DARK)
|
| 294 |
+
return fig
|
tests/test_production_v422.py
CHANGED
|
@@ -66,6 +66,59 @@ def write_labels(root, segment):
|
|
| 66 |
return labels[14] > 0, supervision[14] > 0
|
| 67 |
|
| 68 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
@pytest.fixture
|
| 70 |
def remote(tmp_path, monkeypatch):
|
| 71 |
"""Deux surfaces : « lab » annotée, « bare » sans annotation et de 19 couches seulement."""
|
|
@@ -82,12 +135,14 @@ def remote(tmp_path, monkeypatch):
|
|
| 82 |
{'case': 'bare', 'scroll': 'PHercU', 'label': 'Sans annotation', 'segment': SEGMENT[:-1] + '2', 'volume': VOLUME, 'voxel_um': 9.362,
|
| 83 |
'labels': None, 'origins_yx': None,
|
| 84 |
'provenance': {'scroll': 'PHercU', 'status': 'roll_not_listed_in_model_card', 'segment_status': 'not_listed', 'basis': 'test'}}]}
|
|
|
|
|
|
|
| 85 |
path = tmp_path / 'manifest.json'; path.write_text(json.dumps(manifest))
|
| 86 |
monkeypatch.setattr(surface_manifest, 'MANIFEST', path)
|
| 87 |
local = LocalFileSystem()
|
| 88 |
monkeypatch.setattr(hub_stream, 'default_filesystem',
|
| 89 |
lambda scheme: (local, str(root / scheme) + '/'))
|
| 90 |
-
return SimpleNamespace(root=root, data=data, truth=truth)
|
| 91 |
|
| 92 |
|
| 93 |
def fake_engine(monkeypatch, drift=0.):
|
|
@@ -335,28 +390,30 @@ def test_production_panel_views_are_bounded_and_truthful(storage, remote, monkey
|
|
| 335 |
fake_engine(monkeypatch)
|
| 336 |
rows = ui.probe_rows(storage)
|
| 337 |
assert rows[0][1] == '28 × 1100 × 1300' and 'alignées' in rows[0][5] and 'lié au repère plat' in rows[0][6] and rows[0][7] == 'ok'
|
| 338 |
-
assert rows[1][4] == 'non déclarée' and rows[1][5] == 'aucune'
|
| 339 |
assert ui.latest_summary(storage) == (None, None)
|
| 340 |
result = run(storage, ['lab'], tiles=2, radius=0, device='cpu')
|
| 341 |
report, folder = ui.latest_summary(storage)
|
| 342 |
assert report['rois_done'] == 2 and folder == Path(result['folder']).name
|
| 343 |
table = ui.loop_rows(report['rows'])
|
| 344 |
-
assert len(table) == 2 and len(table[0]) == len(ui.LOOP_HEADERS) and table[0][
|
| 345 |
regions = ui.analysed_rois(storage, 'lab')
|
| 346 |
assert sorted(r['origin_yx'] for r in regions) == sorted(report['plans']['lab']['origins_yx'])
|
| 347 |
chosen = next(r for r in regions if r['origin_yx'] == [512, 512])
|
| 348 |
-
fig,
|
| 349 |
kinds = [t.type for t in fig.data]
|
| 350 |
-
|
|
|
|
| 351 |
assert len(fig.data[0].x) <= MAX_VERTICES and fig.data[-1].surfacecolor.shape == (48, 48)
|
| 352 |
-
assert
|
| 353 |
-
assert
|
|
|
|
| 354 |
# Sans concordance grille/surface, le maillage reste affiché mais aucune ROI n'y est placée.
|
| 355 |
from src import surface_manifest as sm
|
| 356 |
real = sm.surface_contract
|
| 357 |
monkeypatch.setattr(sm, 'surface_contract', lambda s, i: {**real(s, i), 'shape': [28, 2200, 1300]})
|
| 358 |
-
fig, note,
|
| 359 |
-
assert [t.type for t in fig.data] == ['mesh3d'] and 'non établi' in note
|
| 360 |
|
| 361 |
|
| 362 |
def test_dashboard_embeds_the_panel_without_changing_the_fifteen_outputs(storage, remote):
|
|
@@ -383,10 +440,13 @@ def test_shipped_manifest_is_consistent():
|
|
| 383 |
from src.ink_batch import SOURCE
|
| 384 |
surfaces = catalog()['surfaces']
|
| 385 |
assert len({s['case'] for s in surfaces}) == len(surfaces) == 7
|
|
|
|
|
|
|
|
|
|
| 386 |
assert source_uri(next(s for s in surfaces if s['case'] == 'published-w043')) == SOURCE
|
| 387 |
for item in surfaces:
|
| 388 |
assert parse(source_uri(item))[0] == 's3' and item['provenance']['basis']
|
| 389 |
-
if item['labels']:
|
| 390 |
assert all(parse(u)[0] == 'hf' for u in label_uris(item).values())
|
| 391 |
assert {s['scroll'] for s in surfaces} == {'PHerc0139', 'PHerc0841'}
|
| 392 |
|
|
|
|
| 66 |
return labels[14] > 0, supervision[14] > 0
|
| 67 |
|
| 68 |
|
| 69 |
+
def native_xyz(y, x):
|
| 70 |
+
"""Point 3D (voxels du volume natif) du pixel plat y,x : la grille de test est affine."""
|
| 71 |
+
gx, gy = x * .05, y * .05
|
| 72 |
+
return np.stack([100 + 20 * gx, 200 + 20 * gy, 300 + 2 * gx + 3 * gy], -1)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
BRIDGE = lambda p: 4 * p + np.array([10., 20., -500.]) # repère du volume fin
|
| 76 |
+
TO_NATIVE = lambda v, u: (v / 3.8, u / 4.1 + 30) # pixel annoté -> pixel natif (autre grille plate)
|
| 77 |
+
CANVAS = (4224, 5248)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def write_tifxyz(target, xyz, scale):
|
| 81 |
+
import tifffile
|
| 82 |
+
target.mkdir(parents=True)
|
| 83 |
+
(target / 'meta.json').write_text(json.dumps({'format': 'tifxyz', 'type': 'seg', 'scale': scale}))
|
| 84 |
+
for index, axis in enumerate('xyz'):
|
| 85 |
+
tifffile.imwrite(target / (axis + '.tif'), xyz[..., index].astype('float32'))
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def write_transfer_case(root, bridge_shape=(55, 65), normal_shift=0.):
|
| 89 |
+
"""Surface « xfer » : annotations sur une autre grille plate, reliées par un pont et un maillage annoté."""
|
| 90 |
+
import zarr
|
| 91 |
+
write_surface(root, 'seg3', hole=False); write_mesh(root, 'seg3', invalid=((0, 0), (0, 0)))
|
| 92 |
+
gy, gx = np.mgrid[0:bridge_shape[0], 0:bridge_shape[1]]
|
| 93 |
+
write_tifxyz(root / 's3/PHercT/segments/seg3/mesh/seg3-on-20990101000000-2.403um-t2.tifxyz',
|
| 94 |
+
BRIDGE(native_xyz(gy * 20., gx * 20.)), [0.0128, 0.0128])
|
| 95 |
+
rows, cols = np.mgrid[0:212, 0:263]
|
| 96 |
+
y, x = TO_NATIVE(rows * 20., cols * 20.)
|
| 97 |
+
label_xyz = BRIDGE(native_xyz(y, x)); label_xyz[..., 2] += normal_shift
|
| 98 |
+
base = root / 'hf/ink/t/w00'
|
| 99 |
+
write_tifxyz(base, label_xyz, [0.05, 0.05])
|
| 100 |
+
vv, uu = np.mgrid[0:CANVAS[0], 0:CANVAS[1]]
|
| 101 |
+
ny, nx = TO_NATIVE(vv.astype('float32'), uu.astype('float32'))
|
| 102 |
+
inside = lambda y0, y1, x0, x1: (ny >= y0) & (ny < y1) & (nx >= x0) & (nx < x1)
|
| 103 |
+
planes = {'lab': inside(600, 700, 600, 700), 'sup': inside(512, 1024, 512, 1100), 'val': inside(0, 512, 600, 900)}
|
| 104 |
+
for name, plane in planes.items():
|
| 105 |
+
data = np.zeros((5, *CANVAS), 'uint8'); data[2] = plane * 255
|
| 106 |
+
group = zarr.open_group(str(base / (name + '.zarr')), mode='w')
|
| 107 |
+
group.attrs['multiscales'] = [{'datasets': [
|
| 108 |
+
{'path': '0', 'coordinateTransformations': [{'type': 'scale', 'scale': [1., 1., 1.]}]},
|
| 109 |
+
{'path': '5', 'coordinateTransformations': [{'type': 'scale', 'scale': [1., 32., 32.]}]}]}]
|
| 110 |
+
group.create_dataset('0', data=data, chunks=(5, 256, 256), dimension_separator='/')
|
| 111 |
+
group.create_dataset('5', data=data[:, ::32, ::32], chunks=(5, 128, 128))
|
| 112 |
+
entry = {'case': 'xfer', 'scroll': 'PHercV', 'label': 'Annotée par transfert', 'segment': SEGMENT[:-1] + '3', 'volume': VOLUME,
|
| 113 |
+
'voxel_um': 9.362, 'origins_yx': None,
|
| 114 |
+
'labels': {'kind': 'mesh_transfer', 'root': 'hf://buckets/scrollprize/datasets/ink/t/w00', 'labels': 'lab.zarr',
|
| 115 |
+
'supervision': 'sup.zarr', 'validation': 'val.zarr', 'label_mesh': 'hf://buckets/scrollprize/datasets/ink/t/w00',
|
| 116 |
+
'bridge_mesh': SEGMENT[:-1] + '3/mesh/seg3-on-20990101000000-2.403um-t2.tifxyz',
|
| 117 |
+
'label_voxel_um': 2.403, 'tolerance_um': 9.362},
|
| 118 |
+
'provenance': {'scroll': 'PHercV', 'status': 'roll_not_listed_in_model_card', 'segment_status': 'not_listed', 'basis': 'test'}}
|
| 119 |
+
return SimpleNamespace(entry=entry, root=root)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
@pytest.fixture
|
| 123 |
def remote(tmp_path, monkeypatch):
|
| 124 |
"""Deux surfaces : « lab » annotée, « bare » sans annotation et de 19 couches seulement."""
|
|
|
|
| 135 |
{'case': 'bare', 'scroll': 'PHercU', 'label': 'Sans annotation', 'segment': SEGMENT[:-1] + '2', 'volume': VOLUME, 'voxel_um': 9.362,
|
| 136 |
'labels': None, 'origins_yx': None,
|
| 137 |
'provenance': {'scroll': 'PHercU', 'status': 'roll_not_listed_in_model_card', 'segment_status': 'not_listed', 'basis': 'test'}}]}
|
| 138 |
+
extra = write_transfer_case(root)
|
| 139 |
+
manifest['surfaces'].append(extra.entry)
|
| 140 |
path = tmp_path / 'manifest.json'; path.write_text(json.dumps(manifest))
|
| 141 |
monkeypatch.setattr(surface_manifest, 'MANIFEST', path)
|
| 142 |
local = LocalFileSystem()
|
| 143 |
monkeypatch.setattr(hub_stream, 'default_filesystem',
|
| 144 |
lambda scheme: (local, str(root / scheme) + '/'))
|
| 145 |
+
return SimpleNamespace(root=root, data=data, truth=truth, xfer=extra)
|
| 146 |
|
| 147 |
|
| 148 |
def fake_engine(monkeypatch, drift=0.):
|
|
|
|
| 390 |
fake_engine(monkeypatch)
|
| 391 |
rows = ui.probe_rows(storage)
|
| 392 |
assert rows[0][1] == '28 × 1100 × 1300' and 'alignées' in rows[0][5] and 'lié au repère plat' in rows[0][6] and rows[0][7] == 'ok'
|
| 393 |
+
assert rows[1][4] == 'non déclarée' and rows[1][5] == 'aucune' and 'pont 3D vérifié' in rows[2][5]
|
| 394 |
assert ui.latest_summary(storage) == (None, None)
|
| 395 |
result = run(storage, ['lab'], tiles=2, radius=0, device='cpu')
|
| 396 |
report, folder = ui.latest_summary(storage)
|
| 397 |
assert report['rois_done'] == 2 and folder == Path(result['folder']).name
|
| 398 |
table = ui.loop_rows(report['rows'])
|
| 399 |
+
assert len(table) == 2 and len(table[0]) == len(ui.LOOP_HEADERS) and table[0][3] == 'W8' and table[0][4] == 'entraînement'
|
| 400 |
regions = ui.analysed_rois(storage, 'lab')
|
| 401 |
assert sorted(r['origin_yx'] for r in regions) == sorted(report['plans']['lab']['origins_yx'])
|
| 402 |
chosen = next(r for r in regions if r['origin_yx'] == [512, 512])
|
| 403 |
+
fig, locator, note, listed = ui.mesh_view(storage, 'lab', chosen['folder'])
|
| 404 |
kinds = [t.type for t in fig.data]
|
| 405 |
+
# Par ROI : un contour et un numéro ; la ROI ouverte porte en plus la nappe de scores.
|
| 406 |
+
assert kinds.count('mesh3d') == 1 and kinds.count('surface') == 1 and kinds.count('scatter3d') == 4
|
| 407 |
assert len(fig.data[0].x) <= MAX_VERTICES and fig.data[-1].surfacecolor.shape == (48, 48)
|
| 408 |
+
assert len(fig.to_json()) < 3 * 1024**2 and len(locator.to_json()) < 1024**2
|
| 409 |
+
assert sum(t.type == 'scatter' for t in locator.data) == 2 and len(locator.layout.annotations) == 2
|
| 410 |
+
assert 'grille tifxyz vérifiée' in note and 'Aucune paramétrisation UV' in note and '1 = y,x' in note
|
| 411 |
# Sans concordance grille/surface, le maillage reste affiché mais aucune ROI n'y est placée.
|
| 412 |
from src import surface_manifest as sm
|
| 413 |
real = sm.surface_contract
|
| 414 |
monkeypatch.setattr(sm, 'surface_contract', lambda s, i: {**real(s, i), 'shape': [28, 2200, 1300]})
|
| 415 |
+
fig, locator, note, _ = ui.mesh_view(storage, 'lab', chosen['folder'])
|
| 416 |
+
assert [t.type for t in fig.data] == ['mesh3d'] and locator is None and 'non établi' in note
|
| 417 |
|
| 418 |
|
| 419 |
def test_dashboard_embeds_the_panel_without_changing_the_fifteen_outputs(storage, remote):
|
|
|
|
| 440 |
from src.ink_batch import SOURCE
|
| 441 |
surfaces = catalog()['surfaces']
|
| 442 |
assert len({s['case'] for s in surfaces}) == len(surfaces) == 7
|
| 443 |
+
w00 = next(s for s in surfaces if s['case'] == 'pherc0841-w00')['labels']
|
| 444 |
+
assert w00['kind'] == 'mesh_transfer' and parse(w00['bridge_mesh'])[0] == 's3' and parse(w00['label_mesh'])[0] == 'hf'
|
| 445 |
+
assert w00['tolerance_um'] == 9.366 and label_uris({'labels': w00}) is None
|
| 446 |
assert source_uri(next(s for s in surfaces if s['case'] == 'published-w043')) == SOURCE
|
| 447 |
for item in surfaces:
|
| 448 |
assert parse(source_uri(item))[0] == 's3' and item['provenance']['basis']
|
| 449 |
+
if item['labels'] and item['labels'].get('kind') != 'mesh_transfer':
|
| 450 |
assert all(parse(u)[0] == 'hf' for u in label_uris(item).values())
|
| 451 |
assert {s['scroll'] for s in surfaces} == {'PHerc0139', 'PHerc0841'}
|
| 452 |
|
tests/test_validation_v423.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""v4.23.0 : transfert d'annotations par la géométrie 3D, tri géométrique des composantes, dossier de ROI.
|
| 2 |
+
|
| 3 |
+
La surface « xfer » du jeu d'essai a ses annotations sur une autre grille plate (échelles 3,8 et 4,1,
|
| 4 |
+
décalage de 30 px), reliée par un pont et un maillage annoté construits analytiquement : le résultat
|
| 5 |
+
attendu du transfert est donc connu au pixel près.
|
| 6 |
+
"""
|
| 7 |
+
import json
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
import pytest
|
| 12 |
+
|
| 13 |
+
from src.storage import Storage
|
| 14 |
+
from test_production_v422 import fake_engine, native_xyz, remote, write_tifxyz, BRIDGE, TO_NATIVE # noqa: F401
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@pytest.fixture
|
| 18 |
+
def storage(tmp_path):
|
| 19 |
+
s = Storage(tmp_path / 'data', require_mount=False); s.initialize(); return s
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def test_labels_cross_two_flat_grids_through_3d_and_land_on_the_right_pixels(storage, remote):
|
| 23 |
+
from src.hub_stream import Stream
|
| 24 |
+
from src.label_transfer import transfer, build
|
| 25 |
+
from src.surface_manifest import entry
|
| 26 |
+
stream = Stream(storage); item = entry('xfer')
|
| 27 |
+
mapping = build(storage, stream, item)
|
| 28 |
+
assert mapping.affine['residual_p95_um'] < 1e-2 and mapping.affine['linear_scale'] == pytest.approx(4, abs=1e-3)
|
| 29 |
+
# Un pixel natif connu retombe sur son pixel annoté : y = v/3,8 et x = u/4,1 + 30.
|
| 30 |
+
canvas, residual, good = mapping.project(np.array([[700., 800.], [512., 512.]]))
|
| 31 |
+
assert good.all() and residual.max() < .05
|
| 32 |
+
assert np.allclose(canvas, [[700 * 3.8, (800 - 30) * 4.1], [512 * 3.8, (512 - 30) * 4.1]], atol=.05)
|
| 33 |
+
labels, mask, detail = transfer(storage, stream, item, [512, 512])
|
| 34 |
+
expected = np.zeros((512, 512), bool); expected[88:188, 88:188] = True
|
| 35 |
+
assert (labels.astype(bool) ^ expected).sum() <= 2 * 400 # au plus un pixel de bord par côté
|
| 36 |
+
assert (labels.astype(bool) & expected).sum() >= 98 * 98 and mask.mean() > .995
|
| 37 |
+
gate = detail['gate']
|
| 38 |
+
assert gate['mapped_fraction'] == 1.0 and gate['residual_p95_um'] < .05 and gate['positive_pixels'] == int(labels.sum())
|
| 39 |
+
assert gate['supervision_pixels'] > 0 and gate['validation_pixels'] == 0 and gate['tolerance_um'] == 9.362
|
| 40 |
+
assert [e['role'] for e in detail['evidence']] == ['labels', 'supervision', 'validation']
|
| 41 |
+
assert detail['evidence'][0]['planes_with_data'] == [2] and detail['evidence'][0]['network_bytes'] > 0
|
| 42 |
+
# ROI couverte par le masque de validation public seulement : il compte aussi comme zone annotée.
|
| 43 |
+
_, mask, detail = transfer(storage, stream, item, [0, 512])
|
| 44 |
+
assert detail['gate']['validation_pixels'] > 0 and 0 < mask.mean() < 1
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def test_transfer_is_refused_when_the_geometry_does_not_agree(tmp_path, remote):
|
| 48 |
+
from src.hub_stream import Stream
|
| 49 |
+
from src.label_transfer import transfer, TransferRefused
|
| 50 |
+
from src.surface_manifest import entry
|
| 51 |
+
item = entry('xfer')
|
| 52 |
+
base = remote.root / 'hf/ink/t/w00'
|
| 53 |
+
import tifffile
|
| 54 |
+
z = tifffile.imread(base / 'z.tif'); tifffile.imwrite(base / 'z.tif', (z + 30).astype('float32')) # 72 µm hors surface
|
| 55 |
+
first = Storage(tmp_path / 'a', require_mount=False); first.initialize()
|
| 56 |
+
with pytest.raises(TransferRefused, match='projection'):
|
| 57 |
+
transfer(first, Stream(first), item, [512, 512])
|
| 58 |
+
tifffile.imwrite(base / 'z.tif', z.astype('float32'))
|
| 59 |
+
bridge = remote.root / 's3/PHercT/segments/seg3/mesh/seg3-on-20990101000000-2.403um-t2.tifxyz'
|
| 60 |
+
import shutil; shutil.rmtree(bridge)
|
| 61 |
+
gy, gx = np.mgrid[0:54, 0:65]
|
| 62 |
+
write_tifxyz(bridge, BRIDGE(native_xyz(gy * 20., gx * 20.)), [0.0128, 0.0128])
|
| 63 |
+
second = Storage(tmp_path / 'b', require_mount=False); second.initialize()
|
| 64 |
+
with pytest.raises(TransferRefused, match='grille'):
|
| 65 |
+
transfer(second, Stream(second), item, [512, 512])
|
| 66 |
+
shutil.rmtree(bridge)
|
| 67 |
+
gy, gx = np.mgrid[0:55, 0:65]
|
| 68 |
+
warped = BRIDGE(native_xyz(gy * 20., gx * 20.)); warped[..., 0] += 40 * np.sin(gy / 3.) # pont non affine
|
| 69 |
+
write_tifxyz(bridge, warped, [0.0128, 0.0128])
|
| 70 |
+
third = Storage(tmp_path / 'c', require_mount=False); third.initialize()
|
| 71 |
+
with pytest.raises(TransferRefused, match='affine'):
|
| 72 |
+
transfer(third, Stream(third), item, [512, 512])
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def test_refused_transfer_yields_a_report_without_metrics(storage, remote, monkeypatch):
|
| 76 |
+
from src import label_transfer
|
| 77 |
+
from src.unified_pipeline import run
|
| 78 |
+
fake_engine(monkeypatch)
|
| 79 |
+
def refuse(*a, **k): raise label_transfer.TransferRefused('projection : 12.0 % des pixels')
|
| 80 |
+
monkeypatch.setattr(label_transfer, 'transfer', refuse)
|
| 81 |
+
report = run(storage, case='xfer', radius=0, device='cpu', origin=[512, 512])['report']
|
| 82 |
+
assert report['labels_role'] == 'label_transfer_refused' and not report['metrics'] and not report['quality_measured']
|
| 83 |
+
assert report['surface']['label_transfer'] == {'refused': 'projection : 12.0 % des pixels'}
|
| 84 |
+
assert not report['independent_roll_evaluated'] and report['technical_verdict'] == 'passed'
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def test_independent_roi_is_planned_from_public_labels_and_measured(storage, remote, monkeypatch):
|
| 88 |
+
from src.surface_manifest import plan
|
| 89 |
+
from src.multi_surface import run
|
| 90 |
+
fake_engine(monkeypatch)
|
| 91 |
+
planned = plan(storage, 'xfer', 2)
|
| 92 |
+
assert planned['origins_yx'][0] == [512, 512] and 'transfert 3D' in planned['rule'] and planned['prediction_independent']
|
| 93 |
+
result = run(storage, ['xfer'], tiles=1, radius=0, device='cpu')
|
| 94 |
+
row = result['report']['rows'][0]
|
| 95 |
+
assert row['labels_role'] == 'independent_public_annotation' and row['transfer_residual_p95_um'] < .05
|
| 96 |
+
assert row['tp'] + row['fn'] == row['positive_pixels'] > 9000 and row['transfer_refused'] is None
|
| 97 |
+
report = json.loads((Path(result['folder']).parent / row['archive'][:-4] / 'metadata.json').read_text())
|
| 98 |
+
assert report['independent_roll_evaluated'] and report['metrics_scope'].startswith('independent roll')
|
| 99 |
+
assert not report['held_out_evaluated'] and not report['submission_ready'] and not report['legibility_certified']
|
| 100 |
+
assert report['metrics']['forward']['raw']['pixels'] == report['surface']['label_transfer']['annotated_pixels']
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def roi_folder(storage, shapes, reverse_off=(), spread=0.02):
|
| 104 |
+
"""Dossier de ROI minimal : rectangles (y0,y1,x0,x1) à 0,8 dans le sens direct."""
|
| 105 |
+
import tifffile
|
| 106 |
+
folder = storage.path('submissions', 'patch_' + 'c' * 32); folder.mkdir()
|
| 107 |
+
forward = np.full((512, 512), .25, 'float32'); reverse = forward.copy(); binary = np.zeros((512, 512), 'uint8')
|
| 108 |
+
for index, (y0, y1, x0, x1) in enumerate(shapes):
|
| 109 |
+
forward[y0:y1, x0:x1] = .8; binary[y0:y1, x0:x1] = 1
|
| 110 |
+
if index not in reverse_off:
|
| 111 |
+
reverse[y0:y1, x0:x1] = .7
|
| 112 |
+
tifffile.imwrite(folder / 'forward.probabilities.tif', forward); tifffile.imwrite(folder / 'reverse.probabilities.tif', reverse)
|
| 113 |
+
tifffile.imwrite(folder / 'forward.components.tif', binary)
|
| 114 |
+
tifffile.imwrite(folder / 'forward.depth_spread.tif', np.full((512, 512), spread, 'float32'))
|
| 115 |
+
report = {'voxel_um': 10., 'origin_yx': [512, 512]}
|
| 116 |
+
(folder / 'metadata.json').write_text(json.dumps(report))
|
| 117 |
+
return folder
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def test_component_measures_are_geometric_and_exact_on_known_shapes(storage):
|
| 121 |
+
from src.candidates import measure
|
| 122 |
+
folder = roi_folder(storage, [(100, 106, 50, 90), (300, 340, 200, 206), (400, 404, 400, 404)], reverse_off=(2,))
|
| 123 |
+
rows, summary = measure(storage, folder)
|
| 124 |
+
bar, post, dot = rows
|
| 125 |
+
assert [r['area_px'] for r in rows] == [240, 240, 16] and summary['components'] == 3
|
| 126 |
+
assert bar['orientation_deg'] in (0.0, 180.0) and post['orientation_deg'] == 90.0 and bar['elongation'] > 6 and dot['elongation'] == 1.0
|
| 127 |
+
assert bar['major_um'] == pytest.approx(4 * np.sqrt((40**2 - 1) / 12 + 1 / 12) * 10, abs=.1)
|
| 128 |
+
assert bar['centroid_yx'] == [102.5, 69.5] and bar['surface_yx'] == [614.5, 581.5] and bar['bbox_yx'] == [100, 50, 106, 90]
|
| 129 |
+
assert bar['reverse_support'] == 1.0 and dot['reverse_support'] == 0.0 and dot['asymmetry'] == pytest.approx(.55, abs=1e-3)
|
| 130 |
+
assert bar['area_um2'] == 24000.0 and bar['mesh_stretch_yx'] is None and 'truth' not in bar
|
| 131 |
+
assert summary['nearest_neighbour_spacing_um'] > 0 and 'dominant_orientation_deg' in summary
|
| 132 |
+
assert all('transcription' not in key and 'glyph' not in key for r in rows for key in r)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def test_gates_need_enough_annotated_components_then_stay_frozen(storage):
|
| 136 |
+
from src.candidates import calibrate, load_gates, verdict, FEATURES
|
| 137 |
+
rng = np.random.default_rng(3)
|
| 138 |
+
def row(ink, i):
|
| 139 |
+
base = {'area_px': 200 if ink else 12, 'mean_score': .8 if ink else .55, 'reverse_support': .9 if ink else .1,
|
| 140 |
+
'depth_spread_mean': .03, 'elongation': 2.0}
|
| 141 |
+
return {**{k: float(v + rng.normal(0, .01 * (abs(v) + 1))) for k, v in base.items()}, 'truth': 'ink' if ink else 'no_ink',
|
| 142 |
+
'mesh_stretch_yx': [1.02, .97]}
|
| 143 |
+
with pytest.raises(ValueError, match='étalonnage refusé'):
|
| 144 |
+
calibrate(storage, [row(True, i) for i in range(40)] + [row(False, i) for i in range(5)], 'test')
|
| 145 |
+
assert load_gates(storage) is None
|
| 146 |
+
rows = [row(True, i) for i in range(40)] + [row(False, i) for i in range(40)]
|
| 147 |
+
gates = calibrate(storage, rows, 'test')
|
| 148 |
+
assert not gates['frozen'] and set(gates['features']) == set(FEATURES)
|
| 149 |
+
assert gates['features']['area_px']['used_as_gate'] and gates['features']['area_px']['auc'] == 1.0
|
| 150 |
+
assert not gates['features']['depth_spread_mean']['used_as_gate'] and not gates['features']['elongation']['used_as_gate']
|
| 151 |
+
assert 12 < gates['features']['area_px']['threshold'] <= 200
|
| 152 |
+
again = calibrate(storage, [row(True, i) for i in range(60)] + [row(False, i) for i in range(60)], 'autre')
|
| 153 |
+
assert again['frozen'] and again['sample_sha256'] == gates['sample_sha256'] and again['source'] == 'test'
|
| 154 |
+
assert verdict(rows[0], gates) == ('retenu', [])
|
| 155 |
+
state, reasons = verdict(rows[-1], gates)
|
| 156 |
+
assert state == 'écarté' and any(r.startswith('area_px <') for r in reasons)
|
| 157 |
+
assert verdict({**rows[0], 'mesh_stretch_yx': [1.4, 1.0]}, gates)[0] == 'écarté'
|
| 158 |
+
assert verdict({**rows[0], 'mesh_stretch_yx': None}, gates)[1] == ['maillage 3D incomplet autour de la composante']
|
| 159 |
+
assert verdict(rows[0], None) == ('non étalonné', [])
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def test_mesh_stretch_and_unmirrored_close_up(storage, remote):
|
| 163 |
+
from src.hub_stream import Stream
|
| 164 |
+
from src.surface_manifest import entry
|
| 165 |
+
from src.vc3d_bridge import load_tifxyz, local_stretch, roi_figure
|
| 166 |
+
mesh = load_tifxyz(storage, Stream(storage), entry('xfer'))
|
| 167 |
+
stretch = local_stretch(mesh, 700, 700)
|
| 168 |
+
# Grille de test : 1 voxel par pixel en x, √(1 + 0,15²) en y à cause de la pente en z.
|
| 169 |
+
assert stretch == pytest.approx((np.hypot(1, .15), np.hypot(1, .1)), abs=1e-3)
|
| 170 |
+
assert local_stretch(mesh, 5, 5) is None
|
| 171 |
+
scores = np.linspace(0, 1, 512 * 512, dtype='float32').reshape(512, 512)
|
| 172 |
+
fig = roi_figure(mesh, [512, 512], scores, [{'surface_yx': [700., 700.], 'id': 1, 'state': 'non étalonné'}])
|
| 173 |
+
kinds = [t.type for t in fig.data]
|
| 174 |
+
assert kinds == ['mesh3d', 'surface', 'scatter3d', 'scatter3d'] and fig.data[1].surfacecolor.shape == (96, 96)
|
| 175 |
+
assert len(fig.to_json()) < 3 * 1024**2
|
| 176 |
+
# Aucune maille du voisinage ne passe sous la nappe (pas de surfaces confondues).
|
| 177 |
+
x, y = np.array(fig.data[0].x), np.array(fig.data[0].y)
|
| 178 |
+
faces = np.stack([fig.data[0].i, fig.data[0].j, fig.data[0].k], 1)
|
| 179 |
+
to_px = lambda v, offset: (v * 1000 / 9.362 - offset) / 20 * 20
|
| 180 |
+
cx = to_px(x[faces].mean(1), 100); cy = to_px(y[faces].mean(1), 200)
|
| 181 |
+
assert not ((cx > 532) & (cx < 1003) & (cy > 532) & (cy < 1003)).any()
|
| 182 |
+
# Caméra : x plat vers la droite de l'écran, y plat vers le bas — même sens que les images 2D.
|
| 183 |
+
camera = fig.layout.scene.camera
|
| 184 |
+
eye = np.array([camera.eye.x, camera.eye.y, camera.eye.z]); up = np.array([camera.up.x, camera.up.y, camera.up.z])
|
| 185 |
+
right = np.cross(-eye, up)
|
| 186 |
+
ex = native_xyz(700., 701.) - native_xyz(700., 700.); ey = native_xyz(701., 700.) - native_xyz(700., 700.)
|
| 187 |
+
assert right @ ex > 0 and up @ ey < 0
|
| 188 |
+
assert roi_figure(mesh, [700, 900], scores) is None
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def test_dossier_shows_measures_and_an_empty_transcription(storage, remote, monkeypatch):
|
| 192 |
+
from src import production_ui as ui
|
| 193 |
+
from src.candidates import GATES_FILE
|
| 194 |
+
from src.multi_surface import run
|
| 195 |
+
fake_engine(monkeypatch)
|
| 196 |
+
run(storage, ['xfer'], tiles=1, radius=0, device='cpu')
|
| 197 |
+
region = ui.analysed_rois(storage, 'xfer')[0]
|
| 198 |
+
zoom, ct, score, outlined, errors, table, note = ui.dossier_view(storage, 'xfer', region['folder'])
|
| 199 |
+
assert zoom is not None and ct.shape == (512, 512) and score.dtype == np.uint8 and outlined.shape == (512, 512, 3)
|
| 200 |
+
assert errors is not None and errors.shape == (512, 512, 3)
|
| 201 |
+
assert 0 < len(table) <= ui.MAX_ROWS and len(table[0]) == len(ui.COMPONENT_HEADERS) and table[0][1] == 'non étalonné'
|
| 202 |
+
assert 'Transcription : — (vide' in note and 'non étalonné' in note and 'publiques · indépendantes' in note
|
| 203 |
+
assert (outlined == [251, 191, 36]).all(-1).any() and not (outlined == [52, 211, 153]).all(-1).any()
|
| 204 |
+
with pytest.raises(ValueError, match='choisir une ROI'):
|
| 205 |
+
ui.dossier_view(storage, 'xfer', 'patch_' + 'f' * 32)
|
| 206 |
+
# Portes figées présentes : chaque composante reçoit un verdict motivé, toujours sans texte de lecture.
|
| 207 |
+
gates = {'schema': 'unique-candidate-gates/1', 'created_at': 0., 'source': 'test', 'stretch_tolerance': .2,
|
| 208 |
+
'features': {'area_px': {'auc': .9, 'direction': 'min', 'threshold': 20., 'youden_j': .8, 'used_as_gate': True}}}
|
| 209 |
+
storage.json('chunks', GATES_FILE, gates)
|
| 210 |
+
*_, outlined, _, table, note = ui.dossier_view(storage, 'xfer', region['folder'])
|
| 211 |
+
assert {row[1] for row in table} <= {'retenu', 'écarté'} and 'portes figées' in note and 'Transcription : — (vide' in note
|
| 212 |
+
assert any('area_px < 20' in row[2] for row in table if row[1] == 'écarté')
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def test_calibration_from_the_panel_reports_insufficient_samples(storage, remote, monkeypatch):
|
| 216 |
+
from src import production_ui as ui
|
| 217 |
+
from src.multi_surface import run
|
| 218 |
+
fake_engine(monkeypatch)
|
| 219 |
+
run(storage, ['xfer'], tiles=1, radius=0, device='cpu')
|
| 220 |
+
with pytest.raises(ValueError, match='étalonnage refusé'):
|
| 221 |
+
ui.calibrate_gates(storage, 'xfer')
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def test_dashboard_has_the_dossier_controls_behind_authentication(storage, remote):
|
| 225 |
+
from src.controller import Controller
|
| 226 |
+
from src.dashboard import build_dashboard
|
| 227 |
+
from src.unified_pipeline import VERSION
|
| 228 |
+
assert VERSION == '4.23.0'
|
| 229 |
+
page = build_dashboard(Controller(storage), lambda k: k == 'key')
|
| 230 |
+
values = [c['props'].get('value') for c in page.get_config_file()['components'] if c['type'] == 'button']
|
| 231 |
+
assert 'Ouvrir le dossier de la ROI' in values and 'Étalonner les portes de tri (une seule fois)' in values
|
| 232 |
+
execute = next(f for f in page.fns.values() if f.fn and f.fn.__name__ == 'execute')
|
| 233 |
+
assert len(execute.outputs) == 15
|
| 234 |
+
for name, arguments in (('open_dossier', ('bad', 'xfer', '', None)), ('run_calibration', ('bad', None)), ('load_mesh', ('bad', 'xfer', '', None))):
|
| 235 |
+
fn = next(f.fn for f in page.fns.values() if f.fn and f.fn.__name__ == name)
|
| 236 |
+
with pytest.raises(Exception, match='clé d���administration requise'):
|
| 237 |
+
fn(*arguments)
|
| 238 |
+
load = next(f.fn for f in page.fns.values() if f.fn and f.fn.__name__ == 'load_mesh')
|
| 239 |
+
fig, locator, note, update = load('key', 'xfer', '', None)
|
| 240 |
+
assert fig is not None and locator is not None and 'grille tifxyz vérifiée' in note
|