oafheOUfhrzoG commited on
Commit
dd3c4cf
·
verified ·
1 Parent(s): 555cfed

generation pipeline

Browse files
code/README.md ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # `forge_mosaics/` — synthetic bench generation
2
+
3
+ Turns a painting into a LEGO mosaic whose brick grid is known exactly, then
4
+ fragments, corrupts and scatters it. Every label — instance masks, adjacencies,
5
+ poses — is *derived* from the grid, never hand-annotated.
6
+
7
+ ```
8
+ painting → forge_LAR_2mosaic → mosaic2fragments → features → tools
9
+ mosaic + grid fragments + labels GNN input publish / QA
10
+ ```
11
+
12
+ Python 3.11+, `pip install -r requirements.txt`. Run everything from the repository root.
13
+
14
+ ```
15
+ forge_mosaics/
16
+ ├── forge_LAR_2mosaic/ palette · mosaic · cli · batch · wikiart · remono
17
+ ├── mosaic2fragments/ forge_dataset · curriculum · batch · visualize
18
+ ├── features/ fragment_features · collate
19
+ └── tools/ hf_upload · hf_export_tars · qa_sample_hf · qa_overlays · qa_contact_sheets
20
+ ```
21
+
22
+ ## 1. `forge_LAR_2mosaic/` — painting → LEGO mosaic
23
+
24
+ Clean-room, pure Python: Lab quantisation onto a LEGO palette, greedy tiling, render
25
+ with grey joints. Outputs `canvas_mosaic_<id>.png` **and** `piece_grid_<id>.json`,
26
+ the exact position and colour of every brick.
27
+
28
+ | script | role |
29
+ |---|---|
30
+ | `palette.py` | 82 solid LEGO colours, **greys and silvers removed** — the joint detector downstream would take them for joints. Data table, no CLI. |
31
+ | `mosaic.py` | the forge: square crop → Lab quantisation → greedy largest-monochrome-rectangle packing → render. Deterministic. Imported by all the others. |
32
+ | `cli.py` | one image → one mosaic. |
33
+ | `batch.py` | one folder of images → as many mosaics. |
34
+ | `wikiart.py` | streams *N* images from `huggan/wikiart` through the forge, downloading nothing in full. `--max-dominant-frac` rejects near-monochrome paintings, which carry no cut signal. |
35
+ | `remono.py` | re-forges an existing mosaic as **1×1** tiles from its `piece_grid.json`, without re-quantising. The id is kept, so both tilings stay paired. |
36
+
37
+ ```bash
38
+ python3 forge_mosaics/forge_LAR_2mosaic/wikiart.py --n 5000 \
39
+ --out-dir output/inputs --grid 96 --mode tile --max-dominant-frac 0.55
40
+ ```
41
+
42
+ ## 2. `mosaic2fragments/` — mosaic → fragments and labels
43
+
44
+ Joint detection → union-find over cells → pieces → adjacency graph → region growing
45
+ **along the joints** (no piece is ever cut) → corruption → placement → export.
46
+
47
+ | script | role |
48
+ |---|---|
49
+ | `forge_dataset.py` | the full pipeline on **one** mosaic; carries every knob: `--n-frag-min/max`, `--frag-distribution {balanced,compact,ultracompact}`, `--erode-px-min/max --holes-min/max --missing-min/max`, `--placement {scatter,explode}`, `--no-rotation`, `--max-area-loss`. |
50
+ | `curriculum.py` | **the usual entry point.** Replays the *same* mosaics under the *same* seeds across the five levels `L0_explode → L4_strong`, so that only input difficulty varies. Parallel (`--jobs`), resumes where it stopped. |
51
+ | `batch.py` | simpler driver: several mosaics or several seeds, no levels. |
52
+ | `visualize.py` | visual checks: `source_yolo.txt` polygons repainted on `source.png`; with `--recob`, what contour encoding dropped as opposed to what corruption removed. |
53
+
54
+ ```bash
55
+ python3 forge_mosaics/mosaic2fragments/curriculum.py \
56
+ --inputs-glob 'output/inputs/canvas_mosaic_*.png' \
57
+ --frag-distribution balanced --out output --jobs 6
58
+ ```
59
+
60
+ Each instance is one `mosaic_<id>/` folder:
61
+
62
+ | file | role |
63
+ |---|---|
64
+ | `source.png` | fragments scattered on a blank ground — segmentation and VLM **input** |
65
+ | `graph_fragments.json` | nodes only, no edge, no pose — GNN **input** |
66
+ | `source_yolo.txt` | one normalised polygon per fragment — segmentation ground truth |
67
+ | `graph_complete.json` | the same nodes **plus** adjacency edges — GNN target |
68
+ | `gt_layout.json` | exact footprint and pose of each fragment — scores the reconstruction |
69
+ | `target.png` | the assembled mosaic |
70
+ | `fragments/frag_XX.png` | one alpha crop per fragment |
71
+ | `degradation.md` | corruption report (empty means clean) |
72
+
73
+ > Edges are a **label read off the intact grid**, never re-derived from the corrupted
74
+ > geometry: two eroded fragments no longer touch, and their adjacency would be lost —
75
+ > exactly as two real shards no longer fit together.
76
+
77
+ ## 3. `features/` — descriptors and GNN input
78
+
79
+ **Shared** between synthetic and real: works on a (mask, image) pair and knows nothing
80
+ about LEGO, so the same code applies to a mask from the forge or one detected by YOLO
81
+ on a fresco.
82
+
83
+ | script | role |
84
+ |---|---|
85
+ | `fragment_features.py` | contour, simplification under an **area-loss budget** (`--max-area-loss`, 1 % — the polygon stays inscribed in the true outline and the vertex count is an *output*), PCA canonicalisation (rotation-invariant descriptor), then per-fragment and per-side geometric and colour features. |
86
+ | `collate.py` | folds a dataset into one `gnn_ready.npz` per instance under **two contracts**: *dense* (padded to `n_max` + validity mask) and *ragged* (concatenated vertices + per-fragment start index, no `n_max`, for a length-agnostic encoder). Also writes `gnn_meta.json`; `--n-max` forces a value shared across datasets. |
87
+
88
+ ```bash
89
+ for L in output/balanced/L*_*; do
90
+ python3 forge_mosaics/features/collate.py --dataset "$L"
91
+ done
92
+ ```
93
+
94
+ ## 4. `tools/` — publishing and quality control
95
+
96
+ All four Hub scripts take `--repo-id` and assume `huggingface-cli login`.
97
+
98
+ | script | role |
99
+ |---|---|
100
+ | `hf_upload.py` | pushes a folder to the Hub as a dataset. For small volumes. |
101
+ | `hf_export_tars.py` | for large ones: archives **one `.tar.gz` per level**, uploads it, deletes the local archive before the next (a full dataset exceeds the file count a browsable repo supports; peak disk stays one archive). Resumable. |
102
+ | `qa_sample_hf.py` | samples ~1 % of each published dataset **without downloading the archives**: reads the HTTP stream and cuts the connection once *N* mosaics have gone by. The sample is an archive prefix — unbiased as to content, not as to generation order. |
103
+ | `qa_overlays.py` | on that sample, repaints segmentation polygons and encoding loss, at constant content across levels. |
104
+ | `qa_contact_sheets.py` | `target ǀ source` contact sheets and target-only grids: a bad placement, a degenerate mosaic or a repeated painting shows up at a glance. |
code/features/__init__.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Module post-YOLO / pré-GNN — PARTAGÉ entre forge synthétique et chaîne réelle.
2
+
3
+ - fragment_features : (masque, image) → polygon_n (reco B + PCA), side_features, gnn_input.
4
+ - collate : dataset → n_max → padding + masque de validité → entrée GNN à dim fixe.
5
+ """
6
+ from .fragment_features import (
7
+ extract_polygon,
8
+ resample_reflex_aware,
9
+ pca_canonical_rotation,
10
+ compute_fragment_features,
11
+ )
12
+
13
+ __all__ = [
14
+ "extract_polygon",
15
+ "resample_reflex_aware",
16
+ "pca_canonical_rotation",
17
+ "compute_fragment_features",
18
+ ]
code/features/collate.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Préparation des entrées GNN (post-YOLO / pré-GNN) — DEUX contrats dans le même npz.
2
+
3
+ `polygon_n_canonical` et `side_features` ont une longueur VARIABLE par nœud
4
+ (`n_sides`). La dimension fixe qu'exige le GNN porte sur l'**EMBEDDING de nœud**,
5
+ pas sur le polygone brut → deux représentations livrées côte à côte :
6
+
7
+ **(A) pad à n_max + masque** (`polygon_n_canonical`, `side_features`, `valid_mask`)
8
+ — pour un modèle qui consomme des tenseurs denses. `n_max` est calculé sur
9
+ l'ENSEMBLE du dataset. ⚠️ n_max varie par dataset → pas de transfert cross-dataset
10
+ ni vers le réel (RePAIR : contours 403-1457 sommets).
11
+
12
+ **(B) ragged** (`verts_flat`, `sides_flat`, `node_offsets`) — les MÊMES données
13
+ SANS padding, concaténées sur l'axe des sommets ; le nœud i occupe la tranche
14
+ `[node_offsets[i]:node_offsets[i+1]]`. C'est l'entrée naturelle d'un encodeur
15
+ agnostique à la longueur (PointNet/Deep Sets : MLP partagé par sommet +
16
+ scatter-pooling par segment — `torch_scatter.scatter_max(h, seg_ids)`), qui
17
+ supprime n_max et rend le même modèle transférable LEGO↔réel.
18
+
19
+ Numpy pur, sans dépendance torch (le wrap torch_geometric se fait côté GNN,
20
+ ex. option A : `x = concat([gnn_input, poly.flatten(), sides.flatten()])`).
21
+
22
+ Usage :
23
+ nodes_per_graph = [json.load(open(p))['nodes'] for p in graph_fragments_paths]
24
+ n_max = compute_n_max(nodes_per_graph)
25
+ padded = [[pad_node(n, n_max) for n in nodes] for nodes in nodes_per_graph]
26
+ """
27
+ import argparse
28
+ import glob
29
+ import json
30
+ import os
31
+
32
+ import numpy as np
33
+
34
+
35
+ def compute_n_max(nodes_per_graph):
36
+ """max(n_sides) sur tous les nœuds de tous les graphes (cible de padding)."""
37
+ return max((len(n["polygon_n_canonical"])
38
+ for nodes in nodes_per_graph for n in nodes), default=0)
39
+
40
+
41
+ def pad_node(node, n_max):
42
+ """Renvoie les features du nœud à dimension fixe + masque de validité.
43
+
44
+ - gnn_input : (7,) inchangé (déjà fixe)
45
+ - polygon_n_canonical : (n_max, 2) paddé à 0 au-delà de n_sides
46
+ - side_features : (n_max, 5) paddé à 0 au-delà de n_sides
47
+ - valid_mask : (n_max,) 1.0 pour les vrais sommets, 0.0 pour le padding
48
+ """
49
+ poly = np.asarray(node["polygon_n_canonical"], dtype=np.float32)
50
+ sides = np.asarray(node["side_features"], dtype=np.float32)
51
+ n = len(poly)
52
+ if n > n_max:
53
+ raise ValueError(f"n_sides={n} > n_max={n_max} : recalculer n_max sur tout le dataset")
54
+ poly_p = np.zeros((n_max, 2), dtype=np.float32)
55
+ poly_p[:n] = poly
56
+ sides_p = np.zeros((n_max, 5), dtype=np.float32)
57
+ sides_p[:n] = sides
58
+ mask = np.zeros(n_max, dtype=np.float32)
59
+ mask[:n] = 1.0
60
+ return {
61
+ "gnn_input": np.asarray(node["gnn_input"], dtype=np.float32),
62
+ "polygon_n_canonical": poly_p,
63
+ "side_features": sides_p,
64
+ "valid_mask": mask,
65
+ }
66
+
67
+
68
+ def write_dataset_readme(dataset_dir, n_max, n_graphs):
69
+ """README d'arborescence à la racine du dataset (auto-généré par collate)."""
70
+ name = os.path.basename(os.path.normpath(dataset_dir))
71
+ txt = f"""# `{name}/` — mosaïques LEGO fragmentées
72
+
73
+ ## Fichiers par mosaïque (`mosaic_<id>/`)
74
+ | Fichier | Rôle |
75
+ |---|---|
76
+ | `target.png` | mosaïque **complète** = cible de reconstruction / contexte VLM |
77
+ | `source.png` | fragments **éclatés** sur fond blanc = **entrée YOLO** (et entrée VLM) |
78
+ | `source_yolo.txt` | **vérité terrain YOLO-Seg** : 1 polygone/fragment, normalisé `[0,1]` (entraîne YOLO avec `source.png`) |
79
+ | `source_yolo_viz.png` | overlay debug des labels (inspection humaine) — *absent par défaut* (opt-in `--debug`) |
80
+ | `pieces.json` | debug pur (pièces LEGO détectées) ; **n'entraîne PAS le YOLO** (c'est `source_yolo.txt`), lu nulle part — *absent par défaut* (opt-in `--debug`) |
81
+ | `graph_fragments.json` | **ENTRÉE GNN** : nœuds (features/fragment), zéro arête, sans `target_info` |
82
+ | `graph_complete.json` | **CIBLE GNN** : mêmes nœuds + `target_info` (leak) + arêtes (mating graph) |
83
+ | `gt_layout.json` | **GT de RECONSTRUCTION** (réponse finale) : footprint exact + pose `(x,y,rot)` de chaque fragment dans `target.png`. Sert à **scorer l'assemblage** (IoU/Q_pos) APRÈS la tête de pose du GNN / le VLM qui place les fragments |
84
+ | `gnn_ready.npz` | entrée GNN, **2 contrats** : (A) dense pad `n_max={n_max}`+masque ; (B) **ragged** `verts_flat`/`sides_flat`+`node_offsets` (sans n_max, pour encodeur agnostique) |
85
+ | `degradation.md` | rapport de dégradation (0 si clean) |
86
+ | `fragments/frag_XX.png` | crop alpha par fragment = **entrée VLM** |
87
+
88
+ Au niveau dataset : **`gnn_meta.json`** (`n_max={n_max}`, noms de features).
89
+
90
+ ## Schéma d'un nœud (`graph_fragments.json`)
91
+ | Bloc | Contenu | Taille |
92
+ |---|---|---|
93
+ | `node_id` | identifiant stable (référencé par les arêtes) | — |
94
+ | `gnn_input` | `[area, perimeter, R, G, B, bbox_w, bbox_h]` — domaine-agnostique | 7 |
95
+ | `polygon_n_canonical` | contour en repère **PCA canonique** (invariant rotation) | `n_sides`×2 |
96
+ | `side_features` | par côté `[length, angle, R, G, B]` | `n_sides`×5 |
97
+
98
+ `n_sides` **variable** par nœud → paddé à `n_max={n_max}` + masque dans `gnn_ready.npz`.
99
+ ⚠️ **`target_info`** (dans `graph_complete`) = vérité terrain → ne **jamais** donner en entrée.
100
+
101
+ _Régénéré par `forge_mosaics/mosaic2fragments/{{batch,curriculum}}.py` + `forge_mosaics/features/collate.py`._
102
+ """
103
+ open(os.path.join(dataset_dir, "README.md"), "w", encoding="utf-8").write(txt)
104
+
105
+
106
+ def build_dataset(dataset_dir, out_name="gnn_ready.npz", n_max=None):
107
+ """Étape COLLATE (post-YOLO / pré-GNN) : scanne tout le dataset, calcule n_max,
108
+ pad+masque chaque nœud, et écrit par mosaïque un `gnn_ready.npz` (entrée GNN à
109
+ dimension fixe) + un `gnn_meta.json` (n_max + schéma). Numpy pur : les amis
110
+ GNN chargent et wrappent en torch_geometric.Data eux-mêmes (les arêtes/cibles
111
+ restent dans graph_complete.json)."""
112
+ mosaics = sorted(glob.glob(os.path.join(dataset_dir, "mosaic_*")))
113
+ nodes_per = [json.load(open(os.path.join(m, "graph_fragments.json")))["nodes"]
114
+ for m in mosaics]
115
+ observed = compute_n_max(nodes_per)
116
+ if n_max is None:
117
+ n_max = observed # auto : max du dataset (historique)
118
+ elif observed > n_max: # n_max JOINT imposé → doit couvrir
119
+ raise ValueError(f"--n-max {n_max} < max observé {observed} : "
120
+ "choisir un n_max joint qui couvre ce dataset")
121
+ for m, nodes in zip(mosaics, nodes_per):
122
+ if not nodes:
123
+ continue
124
+ padded = [pad_node(n, n_max) for n in nodes]
125
+ # contrat B (ragged) : mêmes données sans padding, concaténées par sommet
126
+ lens = np.array([len(n["polygon_n_canonical"]) for n in nodes], dtype=np.int64)
127
+ np.savez(
128
+ os.path.join(m, out_name),
129
+ gnn_input=np.stack([p["gnn_input"] for p in padded]), # (N,7)
130
+ polygon_n_canonical=np.stack([p["polygon_n_canonical"] for p in padded]), # (N,n_max,2)
131
+ side_features=np.stack([p["side_features"] for p in padded]), # (N,n_max,5)
132
+ valid_mask=np.stack([p["valid_mask"] for p in padded]), # (N,n_max)
133
+ node_id=np.array([n["node_id"] for n in nodes], dtype=np.int64), # (N,)
134
+ verts_flat=np.concatenate( # (Σn,2) ragged
135
+ [np.asarray(n["polygon_n_canonical"], dtype=np.float32) for n in nodes]),
136
+ sides_flat=np.concatenate( # (Σn,5) ragged
137
+ [np.asarray(n["side_features"], dtype=np.float32) for n in nodes]),
138
+ node_offsets=np.concatenate([[0], np.cumsum(lens)]), # (N+1,)
139
+ )
140
+ sample = json.load(open(os.path.join(mosaics[0], "graph_fragments.json")))
141
+ meta = {
142
+ "n_max": n_max,
143
+ "n_max_observed": observed, # max réel du dataset (≠ n_max si joint imposé)
144
+ "n_graphs": len(mosaics),
145
+ "gnn_input_dim": len(sample["gnn_input_feature_names"]),
146
+ "gnn_input_feature_names": sample["gnn_input_feature_names"],
147
+ "side_feature_names": sample["side_feature_names"],
148
+ "note": ("gnn_ready.npz par mosaïque, DEUX contrats : (A) dense = "
149
+ "polygon_n_canonical/side_features paddés à n_max + valid_mask ; "
150
+ "(B) ragged = verts_flat/sides_flat + node_offsets (nœud i = "
151
+ "tranche [offsets[i]:offsets[i+1]]), SANS n_max — pour encodeur "
152
+ "agnostique (PointNet/Deep Sets, scatter-pooling par segment). "
153
+ "Cibles/arêtes : graph_complete.json. Régénérable via "
154
+ "`python3 forge_mosaics/features/collate.py --dataset <dir>`."),
155
+ }
156
+ json.dump(meta, open(os.path.join(dataset_dir, "gnn_meta.json"), "w"),
157
+ indent=2, ensure_ascii=False)
158
+ write_dataset_readme(dataset_dir, n_max, len(mosaics))
159
+ return n_max
160
+
161
+
162
+ def main():
163
+ p = argparse.ArgumentParser(description="Collate post-YOLO → tenseurs GNN à dim fixe")
164
+ p.add_argument("--dataset", required=True, help="dossier dataset (contient mosaic_*/)")
165
+ p.add_argument("--out-name", default="gnn_ready.npz")
166
+ p.add_argument("--n-max", type=int, default=None,
167
+ help="n_max JOINT imposé (au lieu du max du dataset) : le même sur "
168
+ "plusieurs paliers/datasets/le réel → un seul modèle pad+masque "
169
+ "cross-datasets. Erreur si < max observé. Repère : RePAIR réel "
170
+ "≤291 après reco-B ε=1 %% → 304 couvre LEGO et réel")
171
+ args = p.parse_args()
172
+ n_max = build_dataset(args.dataset, args.out_name, n_max=args.n_max)
173
+ print(f"[collate] {args.dataset} : n_max={n_max} → {args.out_name} par mosaïque + gnn_meta.json")
174
+
175
+
176
+ if __name__ == "__main__":
177
+ main()
code/features/fragment_features.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Extraction de features par fragment — module PARTAGÉ (post-YOLO / pré-GNN).
2
+
3
+ Domaine-agnostique : marche sur n'importe quel masque de fragment (+ image),
4
+ qu'il vienne de la forge synthétique LEGO OU de YOLO sur une mosaïque réelle.
5
+ C'est la garantie d'alignement de schéma entre synthétique et réel : le même
6
+ code produit les mêmes features dans les deux chaînes.
7
+
8
+ Contenu : contour, resample reflex-aware (reco B, polygon_n ⊆ polygon_raw),
9
+ canonicalisation PCA (invariance en rotation), et features par fragment
10
+ (géométrie + couleur de bord). Aucune dépendance LEGO ici (pas de studs, pas de
11
+ grille) — aucune notion LEGO ici. Les bits LEGO/GT (adjacence grille, n_pieces en
12
+ métadonnée) restent dans la forge.
13
+ """
14
+ import numpy as np
15
+ import cv2
16
+
17
+
18
+ # ============================================================
19
+ # Contour
20
+ # ============================================================
21
+
22
+ def extract_polygon(mask):
23
+ contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
24
+ if not contours:
25
+ return np.zeros((0, 2), dtype=np.float32)
26
+ cnt = max(contours, key=cv2.contourArea)
27
+ return cnt.reshape(-1, 2).astype(np.float32)
28
+
29
+
30
+ # ============================================================
31
+ # Resample reflex-aware (reco B) : polygon_n ⊆ polygon_raw
32
+ # ============================================================
33
+
34
+ def _polygon_signed_area(P):
35
+ x, y = P[:, 0], P[:, 1]
36
+ return 0.5 * float(np.dot(x, np.roll(y, -1)) - np.dot(y, np.roll(x, -1)))
37
+
38
+
39
+ def _classify_vertices(P):
40
+ """Per vertex: +1 convex, -1 reflex (concave), 0 ~collinear."""
41
+ M = len(P)
42
+ o = np.sign(_polygon_signed_area(P)) or 1.0
43
+ kind = np.zeros(M, dtype=int)
44
+ for i in range(M):
45
+ a, b, c = P[i - 1], P[i], P[(i + 1) % M]
46
+ cross = (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0])
47
+ v = cross * o
48
+ kind[i] = 0 if abs(v) < 1e-6 else (1 if v > 0 else -1)
49
+ return kind
50
+
51
+
52
+ def _clip_to_polygon(poly_enc, poly_raw):
53
+ """Safety clamp: intersect the encoded polygon with the real piece so that
54
+ polygon_n ⊆ polygon_raw is GUARANTEED even on a pathological contour.
55
+ No-op if shapely is unavailable (reflex-aware alone already gives ~0 gain)."""
56
+ try:
57
+ from shapely.geometry import Polygon
58
+ except Exception:
59
+ return poly_enc
60
+ C = Polygon(poly_enc).buffer(0).intersection(Polygon(poly_raw).buffer(0))
61
+ if C.geom_type == 'Polygon':
62
+ polys = [C]
63
+ elif C.geom_type in ('MultiPolygon', 'GeometryCollection'):
64
+ polys = [g for g in C.geoms if g.geom_type == 'Polygon' and not g.is_empty]
65
+ else:
66
+ polys = []
67
+ if not polys:
68
+ return poly_enc
69
+ best = max(polys, key=lambda g: g.area)
70
+ return np.array(best.exterior.coords[:-1], dtype=np.float32)
71
+
72
+
73
+ MAX_AREA_LOSS_DEFAULT = 0.01 # ε : perte d'aire tolérée pour polygon_n (1 %)
74
+
75
+
76
+ def resample_reflex_aware(polygon_raw, n_min=0, clip=True,
77
+ max_area_loss=MAX_AREA_LOSS_DEFAULT):
78
+ """Reco B — simplifie le contour en **budgétant la PERTE D'AIRE**, `n` en sortie.
79
+
80
+ Garantit `polygon_n ⊆ polygon_raw` : on ne *gagne* jamais d'aire, on en perd
81
+ (« comme si les coins étaient ébréchés ») → les fragments réassemblés ne se
82
+ chevauchent jamais, ils laissent des jours (régime physiquement réalisable).
83
+ Renvoie un polygone de longueur VARIABLE.
84
+
85
+ Algorithme = **Visvalingam-Whyatt** (1993) *restreint aux sommets convexes* :
86
+ on retire itérativement le sommet dont le triangle (préc., lui, suiv.) a la
87
+ plus petite aire, tant que la perte CUMULÉE reste ≤ `max_area_loss` (fraction
88
+ de l'aire du polygone). Deux invariants :
89
+ - **seuls les convexes sont retirables** — retirer un sommet reflex
90
+ pontifierait une concavité et **re-gagnerait** de l'aire (viole ⊆ raw) ;
91
+ - les sommets ~colinéaires ont un triangle d'aire nulle → retirés en
92
+ premier, **gratuitement** (c'est le gros du bruit de contour LEGO).
93
+
94
+ ⚠️ **Corrigé le 23/07/2026.** L'implémentation précédente budgétait le NOMBRE
95
+ de sommets (`n_target` ∈ [16,24]) en amorçant `keep` avec tous les reflex :
96
+ comme `#reflex` (médiane **58** sur LEGO) ≥ `n_target` dans **100 %** des
97
+ fragments, la boucle sortait immédiatement et **aucun convexe n'était jamais
98
+ gardé**. Résultat : perte d'aire médiane **21,4 %** (p95 85,8 %, un quart des
99
+ fragments perdant >50 % de leur aire) sur la config k=10-15 du dataset 25k,
100
+ et jusqu'à 99 % à k=2. L'invariant ⊆ raw tenait (pas d'aire fantôme) mais
101
+ l'AMPLEUR de la perte n'était ni bornée ni mesurée. On budgète désormais la
102
+ grandeur qui compte (la fidélité), et `n` en découle.
103
+
104
+ `n_min` : plancher optionnel sur le nombre de sommets (0 = pas de plancher).
105
+ Le plancher réel reste **#reflex**, atteint automatiquement.
106
+ """
107
+ import heapq
108
+
109
+ P = np.asarray(polygon_raw, dtype=np.float32)
110
+ M = len(P)
111
+ if M < 4:
112
+ return P.copy()
113
+
114
+ total_area = abs(_polygon_signed_area(P))
115
+ if total_area <= 0:
116
+ return P.copy()
117
+ budget = max_area_loss * total_area
118
+
119
+ orient = np.sign(_polygon_signed_area(P)) or 1.0
120
+ prev = [(i - 1) % M for i in range(M)]
121
+ nxt = [(i + 1) % M for i in range(M)]
122
+ alive = [True] * M
123
+ n_alive = M
124
+
125
+ def tri(i):
126
+ """(aire du triangle retiré, convexe ?) pour le sommet i dans l'état courant."""
127
+ a, b, c = P[prev[i]], P[i], P[nxt[i]]
128
+ cross = (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0])
129
+ return abs(cross) / 2.0, (cross * orient) >= 0 # ≥ 0 : convexe ou colinéaire
130
+
131
+ heap = []
132
+ for i in range(M):
133
+ a, cvx = tri(i)
134
+ if cvx:
135
+ heapq.heappush(heap, (a, i))
136
+
137
+ lost = 0.0
138
+ while heap and n_alive > 3:
139
+ a, i = heapq.heappop(heap)
140
+ if not alive[i]:
141
+ continue
142
+ a_now, cvx_now = tri(i) # ré-évaluation paresseuse
143
+ if not cvx_now: # devenu reflex → intouchable
144
+ continue
145
+ if a_now > a + 1e-9: # coût périmé → re-pousser
146
+ heapq.heappush(heap, (a_now, i))
147
+ continue
148
+ if lost + a_now > budget: # budget épuisé
149
+ break
150
+ if n_min and n_alive <= n_min:
151
+ break
152
+ alive[i] = False
153
+ n_alive -= 1
154
+ lost += a_now
155
+ p, n = prev[i], nxt[i]
156
+ nxt[p], prev[n] = n, p
157
+ for j in (p, n): # coûts des voisins modifiés
158
+ aj, cj = tri(j)
159
+ if cj and alive[j]:
160
+ heapq.heappush(heap, (aj, j))
161
+
162
+ poly = P[[i for i in range(M) if alive[i]]]
163
+ if clip:
164
+ poly = _clip_to_polygon(poly, P) # filet de sécurité ⊆ raw
165
+ return np.asarray(poly, dtype=np.float32)
166
+
167
+
168
+ # ============================================================
169
+ # Canonicalisation PCA (invariance en rotation)
170
+ # ============================================================
171
+
172
+ def pca_canonical_rotation(mask):
173
+ """Rotation 2×2 amenant le fragment dans son repère PCA canonique (axe
174
+ principal → x), signe déterministe (skewness du 3e moment sur l'axe majeur).
175
+
176
+ Rend la forme INVARIANTE EN ROTATION : un même fragment, à n'importe quelle
177
+ orientation, donne le même descripteur → plus de fuite d'orientation, et
178
+ repère-target ≡ repère-source (ce que produirait YOLO). Rotation PURE
179
+ (det=+1, pas de miroir : la chiralité compte pour le matching). Ambigu pour
180
+ les formes ~symétriques / ~carrées (axe instable) — limitation acceptée.
181
+ """
182
+ ys, xs = np.where(mask > 0)
183
+ if len(xs) < 3:
184
+ return np.eye(2, dtype=np.float64)
185
+ pts = np.stack([xs, ys], axis=1).astype(np.float64)
186
+ pts -= pts.mean(axis=0)
187
+ evals, evecs = np.linalg.eigh(pts.T @ pts)
188
+ u = evecs[:, int(np.argmax(evals))] # axe principal (unitaire)
189
+ if float(((pts @ u) ** 3).sum()) < 0: # désambiguïse le flip 180°
190
+ u = -u
191
+ return np.array([[u[0], u[1]], [-u[1], u[0]]], dtype=np.float64) # u → axe x, det=+1
192
+
193
+
194
+ # ============================================================
195
+ # Features par fragment (géométrie canonique + couleur de bord)
196
+ # ============================================================
197
+
198
+ def _is_joint_pixel(px, target=136, tol=30):
199
+ r, g, b = int(px[0]), int(px[1]), int(px[2])
200
+ return (abs(r - target) < tol and abs(g - target) < tol and abs(b - target) < tol
201
+ and max(r, g, b) - min(r, g, b) < 25)
202
+
203
+
204
+ def _sample_inward(p0, p1, centroid, img, offset=6):
205
+ """Sample piece interior color along a polygon side.
206
+
207
+ The naive midpoint + small offset can land on a LEGO joint (gray) — we
208
+ therefore try a few samples along the side and reject pixels that look like
209
+ joints, falling back to the median of all samples if everything is gray.
210
+ (Sur fresque réelle : à enrichir vers un profil de couleur le long du bord.)
211
+ """
212
+ samples = []
213
+ for t in (0.3, 0.5, 0.7):
214
+ pt = (1 - t) * p0 + t * p1
215
+ inward = centroid - pt
216
+ norm = float(np.linalg.norm(inward))
217
+ if norm < 1e-6:
218
+ continue
219
+ inward = inward / norm * offset
220
+ s = pt + inward
221
+ sx = int(np.clip(s[0], 0, img.shape[1] - 1))
222
+ sy = int(np.clip(s[1], 0, img.shape[0] - 1))
223
+ px = img[sy, sx][:3]
224
+ samples.append(px)
225
+ if not samples:
226
+ cx = int(np.clip(centroid[0], 0, img.shape[1] - 1))
227
+ cy = int(np.clip(centroid[1], 0, img.shape[0] - 1))
228
+ return img[cy, cx][:3].tolist()
229
+ non_joint = [s for s in samples if not _is_joint_pixel(s)]
230
+ pool = non_joint if non_joint else samples
231
+ return np.median(np.array(pool), axis=0).astype(int).tolist()
232
+
233
+
234
+ def compute_fragment_features(polygon_n, area, mean_color, img, polygon_geom=None):
235
+ """GÉOMÉTRIE (perimeter, bbox, length, angle) calculée sur `polygon_geom`
236
+ (repère canonique PCA → invariant en rotation, si fourni) ; COULEUR
237
+ échantillonnée sur `polygon_n` (repère image, pour indexer les pixels).
238
+
239
+ `area` est passé en scalaire (la forge : len(cells)·stud² ; un chemin post-YOLO
240
+ réel : masque.sum()) → fonction 100 % DOMAINE-AGNOSTIQUE (aucune notion LEGO).
241
+ cx,cy = centroïde image (GT de position, pas un input)."""
242
+ geom = polygon_n if polygon_geom is None else np.asarray(polygon_geom, dtype=np.float64)
243
+ centroid_img = polygon_n.mean(axis=0)
244
+ cx, cy = float(centroid_img[0]), float(centroid_img[1])
245
+ closed = np.vstack([geom, geom[0:1]])
246
+ perimeter = float(np.sqrt(((np.diff(closed, axis=0)) ** 2).sum(axis=1)).sum())
247
+ bbox_w = float(geom[:, 0].max() - geom[:, 0].min()) # repère canonique
248
+ bbox_h = float(geom[:, 1].max() - geom[:, 1].min())
249
+
250
+ side_features = []
251
+ n = len(polygon_n)
252
+ for i in range(n):
253
+ g0, g1 = geom[i], geom[(i + 1) % n]
254
+ length = float(np.linalg.norm(g1 - g0))
255
+ angle = float(np.arctan2(g1[1] - g0[1], g1[0] - g0[0])) # angle canonique
256
+ c = _sample_inward(polygon_n[i], polygon_n[(i + 1) % n], centroid_img, img)
257
+ side_features.append([length, angle, float(c[0]), float(c[1]), float(c[2])])
258
+
259
+ global_features = [
260
+ float(area), perimeter, cx, cy,
261
+ float(mean_color[0]), float(mean_color[1]), float(mean_color[2]),
262
+ bbox_w, bbox_h,
263
+ ]
264
+ return global_features, side_features
code/forge_LAR_2mosaic/batch.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Forge locale LAR — dossier d'images -> dataset_inputs/canvas_mosaic_XXX.png
3
+ + piece_grid_XXX.json (numérotés, prêts pour `mosaic2fragments/batch.py`).
4
+
5
+ Exemple :
6
+ python3 forge_LAR_2mosaic/batch.py --input-dir mes_images --out-dir dataset_inputs \
7
+ --grid 96 --stud-size 40
8
+
9
+ Puis la pipeline aval consomme tout :
10
+ python3 mosaic2fragments/batch.py --inputs dataset_inputs/canvas_mosaic_*.png --out dataset
11
+ """
12
+ import argparse
13
+ from pathlib import Path
14
+
15
+ from mosaic import forge_to_files
16
+
17
+ EXTS = {".png", ".jpg", ".jpeg", ".bmp", ".webp", ".tif", ".tiff", ".gif"}
18
+
19
+
20
+ def parse_args():
21
+ p = argparse.ArgumentParser(description="Dossier d'images -> mosaïques LEGO + GT.")
22
+ p.add_argument("--input-dir", required=True, help="dossier d'images sources")
23
+ p.add_argument("--out-dir", default="dataset_inputs", help="dossier de sortie")
24
+ p.add_argument("--grid", type=int, default=96, help="studs par côté")
25
+ p.add_argument("--stud-size", type=int, default=40, help="px par stud (≥40)")
26
+ p.add_argument("--joint-px", type=int, default=None, help="largeur du joint (défaut ~3)")
27
+ p.add_argument("--mode", choices=["tile", "plate", "brick", "mono"], default="tile",
28
+ help="jeu de pièces LEGO (tile par défaut, max 2×6 ; plate = jusqu'à 4×4/4×10)")
29
+ p.add_argument("--big-plates", action="store_true",
30
+ help="réactive 4×8/4×10 (décochées par défaut sur le site)")
31
+ p.add_argument("--start-index", type=int, default=0, help="indice de départ du nom")
32
+ p.add_argument("--max-dominant-frac", type=float, default=None,
33
+ help="garde-fou : rejeter une image si une couleur LEGO couvre > cette "
34
+ "fraction des cellules (aplats monochromes). None = désactivé")
35
+ return p.parse_args()
36
+
37
+
38
+ def main():
39
+ a = parse_args()
40
+ imgs = sorted(p for p in Path(a.input_dir).iterdir()
41
+ if p.suffix.lower() in EXTS)
42
+ if not imgs:
43
+ raise SystemExit(f"Aucune image dans {a.input_dir} (extensions {sorted(EXTS)})")
44
+ out = Path(a.out_dir)
45
+ out.mkdir(parents=True, exist_ok=True)
46
+ print(f"{len(imgs)} image(s) -> {out}/")
47
+ made = rejected = 0
48
+ for k, src in enumerate(imgs, start=a.start_index):
49
+ png = out / f"canvas_mosaic_{k:03d}.png"
50
+ js = out / f"piece_grid_{k:03d}.json"
51
+ g = forge_to_files(str(src), str(png), str(js),
52
+ grid_w=a.grid, grid_h=a.grid,
53
+ stud_size=a.stud_size, joint_px=a.joint_px,
54
+ mode=a.mode, big_plates=a.big_plates,
55
+ max_dominant_frac=a.max_dominant_frac)
56
+ if g.get("rejected"): # garde-fou : aplat monochrome
57
+ rejected += 1
58
+ print(f" [{k:03d}] {src.name:30s} -> REJETÉ (couleur dominante {g['dominant_frac']:.0%})")
59
+ continue
60
+ made += 1
61
+ print(f" [{k:03d}] {src.name:30s} -> {png.name} ({g['n_pieces']} pièces)")
62
+ print(f"Fait : {made} mosaïques (rejetées par garde-fou : {rejected}).")
63
+ print(f"Ensuite : python3 forge_mosaics/mosaic2fragments/batch.py --inputs {out}/canvas_mosaic_*.png --out dataset")
64
+
65
+
66
+ if __name__ == "__main__":
67
+ main()
code/forge_LAR_2mosaic/cli.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Forge locale LAR — une image -> canvas_mosaic.png + piece_grid.json.
3
+
4
+ Exemple :
5
+ python3 forge_LAR_2mosaic/cli.py --input photo.jpg --out-png out/canvas_mosaic.png \
6
+ --out-json out/piece_grid.json --grid 96 --stud-size 40
7
+ """
8
+ import argparse
9
+ from pathlib import Path
10
+
11
+ from mosaic import forge_to_files
12
+
13
+
14
+ def parse_args():
15
+ p = argparse.ArgumentParser(description="Image -> mosaïque LEGO (tile/plate/brick) + GT.")
16
+ p.add_argument("--input", required=True, help="image source (jpg/png/…)")
17
+ p.add_argument("--out-png", help="chemin du canvas_mosaic.png (défaut : à côté de --input)")
18
+ p.add_argument("--out-json", help="chemin du piece_grid.json")
19
+ p.add_argument("--grid", type=int, default=96, help="studs par côté (48/64/96/100/128)")
20
+ p.add_argument("--stud-size", type=int, default=40, help="px par stud (≥40)")
21
+ p.add_argument("--joint-px", type=int, default=None, help="largeur du joint (défaut ~3)")
22
+ p.add_argument("--mode", choices=["tile", "plate", "brick", "mono"], default="tile",
23
+ help="jeu de pièces LEGO (tile par défaut ; mono = 1×1 seul, ultracompact)")
24
+ p.add_argument("--big-plates", action="store_true",
25
+ help="réactive 4×8/4×10 (décochées par défaut sur le site)")
26
+ return p.parse_args()
27
+
28
+
29
+ def main():
30
+ a = parse_args()
31
+ out_png = a.out_png or str(Path(a.input).with_name("canvas_mosaic.png"))
32
+ out_json = a.out_json or str(Path(out_png).with_name("piece_grid.json"))
33
+ grid = forge_to_files(
34
+ a.input, out_png, out_json,
35
+ grid_w=a.grid, grid_h=a.grid, stud_size=a.stud_size, joint_px=a.joint_px,
36
+ mode=a.mode, big_plates=a.big_plates,
37
+ )
38
+ print(f"{out_png} ({grid['grid_width']}×{grid['grid_height']} studs, mode={grid['mode']}, "
39
+ f"max {grid['max_piece'][0]}×{grid['max_piece'][1]}, "
40
+ f"{grid['n_pieces']} pièces, joint {grid['joint_width_px']}px)")
41
+ print(f"{out_json}")
42
+
43
+
44
+ if __name__ == "__main__":
45
+ main()
code/forge_LAR_2mosaic/mosaic.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Forge de mosaïques LEGO « variable-tile/plate/brick » — clean-room, Python pur.
2
+
3
+ Remplace lego-art-remix.com pour notre usage : image quelconque → mosaïque LEGO
4
+ à pièces plates de tailles variables (1×1 … 4×10) avec joints gris, PLUS la
5
+ vérité-terrain exacte des pièces (`piece_grid.json`).
6
+
7
+ On NE copie aucun code de l'outil source (GPL-3.0) : on réimplémente la logique
8
+ publique (quantif vers palette + packing glouton du plus grand rectangle). Les
9
+ JEUX DE DIMENSIONS et n° de pièce BrickLink par mode sont des FAITS extraits de
10
+ `algo.js` (TILE/PLATE/BRICK_DIMENSIONS_TO_PART_ID). Sortie au FORMAT attendu par
11
+ `mosaic2fragments/forge_dataset.py` (carré, ≥40 px/stud, joints ~RGB(136), palette sans gris).
12
+
13
+ Pipeline :
14
+ 1. crop carré + downsample area-average à grid×grid (1 couleur/cellule)
15
+ 2. quantif nearest-color en espace Lab vers la palette LEGO (sans gris)
16
+ 3. packing glouton : plus grand rectangle MONOCHROME d'abord (aire ↓, comme le
17
+ site) ; reste comblé en 1×1
18
+ 4. rendu : pièces plates pleines + joints gris ; export PNG + piece_grid.json
19
+
20
+ Déterministe (aucun aléa) : même image + mêmes params → même sortie.
21
+ """
22
+ import json
23
+ from pathlib import Path
24
+
25
+ import numpy as np
26
+ from PIL import Image
27
+
28
+ from palette import LEGO_PALETTE, JOINT_COLOR, hex_of
29
+
30
+
31
+ # ============================================================
32
+ # Jeux de dimensions LEGO par mode (studs) + n° de pièce BrickLink.
33
+ # Faits extraits de lego-art-remix/app/js/algo.js (clean-room).
34
+ # ============================================================
35
+
36
+ TILE_DIMS = { # "Variable Tile" (plat, lisse)
37
+ (1, 1): "3070b", (1, 2): "3069b", (1, 3): "63864", (1, 4): "2431",
38
+ (1, 6): "6636", (1, 8): "4162", (2, 2): "3068b", (2, 3): "26603",
39
+ (2, 4): "87079", (2, 6): "69729",
40
+ }
41
+ PLATE_DIMS = { # "Variable Plate" (le + de tailles)
42
+ (1, 1): "3024", (1, 2): "3023", (1, 3): "3623", (1, 4): "3710",
43
+ (1, 6): "3666", (1, 8): "3460", (2, 2): "3022", (2, 3): "3021",
44
+ (2, 4): "3020", (2, 6): "3795", (2, 8): "3034", (4, 4): "3031",
45
+ (4, 8): "3035", (4, 10): "3030",
46
+ }
47
+ BRICK_DIMS = { # "Variable Brick"
48
+ (1, 1): "3005", (1, 2): "3004", (1, 3): "3622", (1, 4): "3010",
49
+ (1, 6): "3009", (1, 8): "3008", (2, 2): "3003", (2, 3): "3002",
50
+ (2, 4): "3001", (2, 6): "2456", (2, 8): "3007",
51
+ }
52
+ MONO_DIMS = {(1, 1): "3070b"} # 1×1 SEUL (mode ultracompact)
53
+ MODE_DIMS = {"tile": TILE_DIMS, "plate": PLATE_DIMS, "brick": BRICK_DIMS, "mono": MONO_DIMS}
54
+ # Le site DÉCOCHE par défaut les plus grosses plates (UI : DEFAULT_DISABLED_DEPTH_PLATES).
55
+ DEFAULT_DISABLED = {(4, 8), (4, 10)}
56
+
57
+
58
+ def build_allowed_parts(mode="tile", big_plates=False):
59
+ """Liste (w, h, part_id) pour le mode donné, 2 orientations, triée comme le
60
+ site : aire décroissante puis plus petite 1re dimension d'abord (déterministe).
61
+ `big_plates=True` réactive 4×8/4×10 (décochées par défaut sur le site)."""
62
+ dims = dict(MODE_DIMS[mode])
63
+ if not big_plates:
64
+ for d in DEFAULT_DISABLED:
65
+ dims.pop(d, None)
66
+ seen, parts = set(), []
67
+ for (a, b), pid in dims.items():
68
+ for w, h in {(a, b), (b, a)}:
69
+ if (w, h) not in seen:
70
+ seen.add((w, h))
71
+ parts.append((w, h, pid))
72
+ parts.sort(key=lambda p: (p[0] * p[1], -p[0]), reverse=True)
73
+ return parts
74
+
75
+
76
+ # ============================================================
77
+ # Espace couleur : sRGB [0,255] -> CIE Lab (D65)
78
+ # ============================================================
79
+
80
+ def srgb_to_lab(rgb):
81
+ """rgb : (..., 3) en [0,255] -> Lab (..., 3). Pur numpy (pas de dépendance)."""
82
+ c = np.asarray(rgb, dtype=np.float64) / 255.0
83
+ lin = np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4)
84
+ r, g, b = lin[..., 0], lin[..., 1], lin[..., 2]
85
+ x = 0.4124 * r + 0.3576 * g + 0.1805 * b
86
+ y = 0.2126 * r + 0.7152 * g + 0.0722 * b
87
+ z = 0.0193 * r + 0.1192 * g + 0.9505 * b
88
+ x /= 0.95047; z /= 1.08883 # point blanc D65 (Yn = 1)
89
+ def f(t):
90
+ return np.where(t > 0.008856, np.cbrt(t), 7.787 * t + 16.0 / 116.0)
91
+ fx, fy, fz = f(x), f(y), f(z)
92
+ return np.stack([116.0 * fy - 16.0, 500.0 * (fx - fy), 200.0 * (fy - fz)], axis=-1)
93
+
94
+
95
+ # ============================================================
96
+ # Étapes 1-2 : image -> grille d'indices de palette
97
+ # ============================================================
98
+
99
+ def image_to_color_grid(image, grid_w, grid_h):
100
+ """Crop carré centré + downsample area-average -> (grid_h, grid_w, 3) uint8.
101
+ `image` : chemin OU objet PIL.Image (utile pour le streaming wikiart)."""
102
+ im = (image if isinstance(image, Image.Image) else Image.open(image)).convert("RGB")
103
+ w, h = im.size
104
+ s = min(w, h) # crop carré centré
105
+ im = im.crop(((w - s) // 2, (h - s) // 2, (w - s) // 2 + s, (h - s) // 2 + s))
106
+ im = im.resize((grid_w, grid_h), Image.BOX) # moyenne par cellule
107
+ return np.asarray(im, dtype=np.uint8)
108
+
109
+
110
+ def quantize_to_palette(color_grid, palette=LEGO_PALETTE):
111
+ """(H,W,3) -> (H,W) indices de la palette (nearest en Lab)."""
112
+ pal = np.array(palette, dtype=np.float64)
113
+ pal_lab = srgb_to_lab(pal) # (P,3)
114
+ cells_lab = srgb_to_lab(color_grid.reshape(-1, 3)) # (H*W,3)
115
+ d = ((cells_lab[:, None, :] - pal_lab[None, :, :]) ** 2).sum(-1) # (H*W,P)
116
+ idx = d.argmin(1).reshape(color_grid.shape[:2])
117
+ return idx.astype(np.int32)
118
+
119
+
120
+ # ============================================================
121
+ # Étape 3 : packing glouton du plus grand rectangle monochrome
122
+ # ============================================================
123
+
124
+ def pack_variable_tiles(idx_grid, allowed_parts):
125
+ """Glouton : pose le plus grand rectangle MONOCHROME possible, sans
126
+ chevauchement, en balayant en row-major ; reste comblé par des 1×1.
127
+
128
+ `allowed_parts` : liste (w, h, part_id) déjà triée (aire ↓). Retourne la
129
+ liste des pièces (col, row, width, height, color_idx, part_id). Chaque pièce
130
+ est mono-couleur (une pièce LEGO = une couleur) ; deux pièces voisines de même
131
+ couleur restent séparées par un joint -> deux pièces distinctes en aval.
132
+ """
133
+ H, W = idx_grid.shape
134
+ occupied = np.zeros((H, W), dtype=bool)
135
+ pieces = []
136
+ for pw, ph, pid in allowed_parts:
137
+ if pw > W or ph > H:
138
+ continue
139
+ for r in range(H - ph + 1):
140
+ for c in range(W - pw + 1):
141
+ if occupied[r:r + ph, c:c + pw].any():
142
+ continue
143
+ block = idx_grid[r:r + ph, c:c + pw]
144
+ if (block == block[0, 0]).all():
145
+ occupied[r:r + ph, c:c + pw] = True
146
+ pieces.append((c, r, pw, ph, int(block[0, 0]), pid))
147
+ # garde-fou : toute cellule restante -> 1×1 (ne devrait pas arriver)
148
+ unit_pid = next((pid for w, h, pid in allowed_parts if (w, h) == (1, 1)), None)
149
+ for r, c in np.argwhere(~occupied):
150
+ pieces.append((int(c), int(r), 1, 1, int(idx_grid[r, c]), unit_pid))
151
+ return pieces
152
+
153
+
154
+ # ============================================================
155
+ # Étape 4 : rendu PNG (pièces plates + joints gris)
156
+ # ============================================================
157
+
158
+ def render_mosaic(pieces, grid_w, grid_h, stud_size, joint_px, palette=LEGO_PALETTE):
159
+ """Fond gris (joints) + chaque pièce peinte en retrait de joint_px/2 sur
160
+ chaque bord -> joint de joint_px px entre pièces voisines. Aucun anti-alias :
161
+ pixels de pièce = couleur palette exacte, pixels de joint = RGB(136) exact."""
162
+ H_px, W_px = grid_h * stud_size, grid_w * stud_size
163
+ img = np.empty((H_px, W_px, 3), dtype=np.uint8)
164
+ img[:] = JOINT_COLOR
165
+ li, ri = joint_px - joint_px // 2, joint_px // 2 # ceil / floor -> joint exact
166
+ for c, r, w, h, ci, _pid in pieces:
167
+ x0, y0 = c * stud_size + li, r * stud_size + li
168
+ x1, y1 = (c + w) * stud_size - ri, (r + h) * stud_size - ri
169
+ img[y0:y1, x0:x1] = palette[ci]
170
+ return Image.fromarray(img, "RGB")
171
+
172
+
173
+ # ============================================================
174
+ # Orchestration
175
+ # ============================================================
176
+
177
+ def forge_mosaic(image, grid_w=96, grid_h=96, stud_size=40, joint_px=None,
178
+ mode="tile", big_plates=False, palette=LEGO_PALETTE, source_name=None,
179
+ max_dominant_frac=None):
180
+ """image (chemin ou PIL.Image) -> (PIL.Image mosaïque, dict piece_grid). mode: tile|plate|brick.
181
+
182
+ Garde-fou `max_dominant_frac` (∈ ]0,1]) : si une seule couleur de palette couvre
183
+ > cette fraction des cellules, l'image est REJETÉE → renvoie `(None, stats)`.
184
+ Cible : les peintures (souvent impressionnistes) à variations infimes d'une même
185
+ couleur, qui s'effondrent en un gros aplat monochrome une fois quantifiées (peu de
186
+ pièces, détection de joints faussée). None par défaut = garde-fou désactivé.
187
+ """
188
+ if joint_px is None:
189
+ joint_px = max(2, round(stud_size * 0.075)) # ~3 px à 40 px/stud
190
+ allowed = build_allowed_parts(mode, big_plates)
191
+ color_grid = image_to_color_grid(image, grid_w, grid_h)
192
+ idx_grid = quantize_to_palette(color_grid, palette)
193
+ counts = np.bincount(idx_grid.ravel(), minlength=len(palette))
194
+ dominant_frac = float(counts.max() / idx_grid.size)
195
+ n_colors = int((counts > 0).sum())
196
+ if max_dominant_frac is not None and dominant_frac > max_dominant_frac:
197
+ return None, {"rejected": True, "reason": "dominant_color",
198
+ "dominant_frac": dominant_frac, "n_colors": n_colors,
199
+ "max_dominant_frac": max_dominant_frac}
200
+ pieces = pack_variable_tiles(idx_grid, allowed)
201
+ img = render_mosaic(pieces, grid_w, grid_h, stud_size, joint_px, palette)
202
+ piece_grid = {
203
+ "grid_width": grid_w,
204
+ "grid_height": grid_h,
205
+ "stud_size_px": stud_size,
206
+ "joint_width_px": joint_px,
207
+ "joint_color_rgb": list(JOINT_COLOR),
208
+ "mode": mode,
209
+ "max_piece": list(max((p[:2] for p in allowed), key=lambda d: d[0] * d[1])),
210
+ "source_image": source_name or (Path(image).name if isinstance(image, (str, Path)) else "image"),
211
+ "dominant_frac": dominant_frac,
212
+ "n_colors": n_colors,
213
+ "n_pieces": len(pieces),
214
+ "n_cells": grid_w * grid_h,
215
+ "pieces": [
216
+ {"col": c, "row": r, "width": w, "height": h,
217
+ "part_id": pid, "color_rgb": list(palette[ci]),
218
+ "color_hex": hex_of(palette[ci])}
219
+ for c, r, w, h, ci, pid in pieces
220
+ ],
221
+ }
222
+ return img, piece_grid
223
+
224
+
225
+ def forge_to_files(image_path, out_png, out_json, **kw):
226
+ img, grid = forge_mosaic(image_path, **kw)
227
+ if img is None: # rejeté par le garde-fou
228
+ return grid # stats, rien écrit
229
+ Path(out_png).parent.mkdir(parents=True, exist_ok=True)
230
+ img.save(out_png)
231
+ Path(out_json).write_text(json.dumps(grid, indent=2))
232
+ return grid
code/forge_LAR_2mosaic/palette.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Palette LEGO — couleurs solides BrickLink, SANS les gris/argentés.
2
+
3
+ Les valeurs hex sont des FAITS (couleurs LEGO officielles, non protégeables) ;
4
+ elles ont été extraites de `bricklink-colors.js` (lego-art-remix, GPL-3.0) puis
5
+ filtrées hors-ligne. AUCUN code de l'outil source n'est importé ici (clean-room).
6
+
7
+ Filtre appliqué : on retire toute couleur « confusable joint », i.e. quasi-grise
8
+ (max-min des canaux < 25) ET d'intensité moyenne (70 ≤ moyenne ≤ 200). C'est la
9
+ fenêtre où le détecteur de joints de `mosaic2fragments/` (gris ~RGB 136 ± 30) ferait un
10
+ faux positif. Blanc (255) et Noir (33) sont conservés (loin de 136).
11
+ """
12
+
13
+ # (R, G, B) — 82 couleurs LEGO solides, gris/argent retirés.
14
+ LEGO_PALETTE = [
15
+ (255, 255, 255), # White
16
+ (232, 232, 232), # Very Light Gray
17
+ (228, 232, 232), # Very Light Bluish Gray
18
+ ( 33, 33, 33), # Black
19
+ (106, 14, 21), # Dark Red
20
+ (179, 0, 6), # Red
21
+ (181, 44, 32), # Rust
22
+ (248, 131, 121), # Coral
23
+ (244, 92, 64), # Salmon
24
+ (255, 222, 220), # Light Salmon
25
+ (140, 107, 107), # Sand Red
26
+ (137, 53, 29), # Reddish Brown
27
+ ( 83, 33, 21), # Brown
28
+ ( 51, 0, 0), # Dark Brown
29
+ (144, 116, 80), # Dark Tan
30
+ (222, 198, 156), # Tan
31
+ (254, 204, 176), # Light Nougat
32
+ (255, 175, 125), # Nougat
33
+ (227, 160, 91), # Medium Nougat
34
+ (231, 139, 62), # Dark Nougat
35
+ (161, 108, 66), # Medium Brown
36
+ (179, 105, 78), # Fabuland Brown
37
+ (239, 145, 33), # Fabuland Orange
38
+ (230, 136, 29), # Earth Orange
39
+ (179, 84, 8), # Dark Orange
40
+ (250, 89, 71), # Neon Orange
41
+ (255, 126, 20), # Orange
42
+ (255, 165, 49), # Medium Orange
43
+ (247, 186, 48), # Bright Light Orange
44
+ (247, 173, 99), # Light Orange
45
+ (230, 192, 93), # Very Light Orange
46
+ (221, 152, 46), # Dark Yellow
47
+ (247, 209, 23), # Yellow
48
+ (243, 224, 85), # Bright Light Yellow
49
+ (255, 227, 131), # Light Yellow
50
+ (235, 238, 143), # Light Lime
51
+ (223, 238, 165), # Yellowish Green
52
+ (188, 239, 102), # Neon Green
53
+ (189, 198, 24), # Medium Lime
54
+ (166, 202, 85), # Lime
55
+ (124, 144, 81), # Olive Green
56
+ ( 46, 85, 67), # Dark Green
57
+ ( 0, 100, 46), # Green
58
+ ( 16, 203, 49), # Bright Green
59
+ ( 98, 245, 142), # Medium Green
60
+ (165, 219, 181), # Light Green
61
+ (118, 162, 144), # Sand Green
62
+ ( 0, 138, 128), # Dark Turquoise
63
+ ( 49, 181, 202), # Light Turquoise
64
+ (181, 211, 214), # Aqua
65
+ (204, 255, 255), # Light Aqua
66
+ ( 20, 48, 68), # Dark Blue
67
+ ( 0, 87, 166), # Blue
68
+ ( 51, 153, 255), # Dark Azure
69
+ ( 66, 192, 251), # Medium Azure
70
+ ( 97, 175, 255), # Medium Blue
71
+ (107, 173, 214), # Maersk Blue
72
+ (159, 195, 233), # Bright Light Blue
73
+ (180, 210, 227), # Light Blue
74
+ (125, 191, 221), # Sky Blue
75
+ ( 90, 113, 132), # Sand Blue
76
+ ( 80, 108, 239), # Blue-Violet
77
+ ( 32, 50, 176), # Dark Blue-Violet
78
+ ( 52, 72, 164), # Violet
79
+ (147, 145, 228), # Medium Violet
80
+ (201, 202, 226), # Light Violet
81
+ ( 95, 38, 131), # Dark Purple
82
+ (165, 73, 156), # Purple
83
+ (218, 112, 214), # Light Purple
84
+ (136, 94, 158), # Medium Lavender
85
+ (224, 170, 217), # Clikits Lavender
86
+ (177, 140, 191), # Lavender
87
+ (181, 125, 165), # Sand Purple
88
+ (181, 41, 82), # Magenta
89
+ (200, 112, 128), # Dark Pink
90
+ (247, 133, 177), # Medium Dark Pink
91
+ (255, 187, 255), # Bright Pink
92
+ (255, 192, 203), # Pink
93
+ (255, 225, 255), # Light Pink
94
+ (255, 252, 0), # Neon Yellow
95
+ (231, 149, 0), # Pearl Gold
96
+ (217, 197, 148), # Medium Tan
97
+ ]
98
+
99
+ JOINT_COLOR = (136, 136, 136) # gris des joints — RGB(136) ≈ rendu lego-art-remix
100
+
101
+
102
+ def hex_of(rgb):
103
+ return "#{:02x}{:02x}{:02x}".format(*rgb)
code/forge_LAR_2mosaic/remono.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Re-forge une mosaïque existante en mode MONO (tuiles 1×1) — pour `ultracompact`.
3
+
4
+ Entrée = le `piece_grid_<uuid>.json` d'une mosaïque déjà forgée (n'importe quel
5
+ mode) : il porte la couleur EXACTE de chaque cellule → on reconstruit la même
6
+ image de mosaïque, mais où chaque cellule est une pièce 1×1 (joints partout).
7
+ Aucune re-quantification (repasser le canvas rendu dans la forge moyennerait les
8
+ joints gris dans les cellules) ; l'uuid est conservé → l'appariement des
9
+ curriculums (même mosaïque de base) reste valable entre variable-tile et mono.
10
+
11
+ Usage :
12
+ python3 forge_mosaics/forge_LAR_2mosaic/remono.py \
13
+ --piece-grids 'output/wikiart_inputs/piece_grid_*.json' \
14
+ --out-dir output/wikiart_inputs_mono [--limit 100]
15
+ """
16
+ import argparse
17
+ import glob
18
+ import json
19
+ from pathlib import Path
20
+
21
+ import numpy as np
22
+
23
+ import sys
24
+ sys.path.insert(0, str(Path(__file__).parent))
25
+ from mosaic import render_mosaic, MONO_DIMS, JOINT_COLOR # noqa: E402
26
+
27
+
28
+ def mono_from_piece_grid(pg):
29
+ """piece_grid dict (mode quelconque) -> (PIL.Image mono, piece_grid mono)."""
30
+ W, H = pg["grid_width"], pg["grid_height"]
31
+ stud, joint = pg["stud_size_px"], pg["joint_width_px"]
32
+ # 1) grille de couleurs exacte depuis les pièces (couverture 1× garantie)
33
+ grid = np.zeros((H, W, 3), dtype=np.uint8)
34
+ for p in pg["pieces"]:
35
+ c, r, w, h = p["col"], p["row"], p["width"], p["height"]
36
+ grid[r:r + h, c:c + w] = p["color_rgb"]
37
+ # 2) palette locale = couleurs distinctes de CETTE mosaïque (rendu exact)
38
+ colors = np.unique(grid.reshape(-1, 3), axis=0)
39
+ lut = {tuple(c): i for i, c in enumerate(colors)}
40
+ unit_pid = MONO_DIMS[(1, 1)]
41
+ pieces = [(c, r, 1, 1, lut[tuple(grid[r, c])], unit_pid)
42
+ for r in range(H) for c in range(W)]
43
+ img = render_mosaic(pieces, W, H, stud, joint, palette=colors)
44
+ piece_grid = {
45
+ **{k: pg[k] for k in ("grid_width", "grid_height", "stud_size_px",
46
+ "joint_width_px", "source_image")},
47
+ "joint_color_rgb": list(JOINT_COLOR),
48
+ "mode": "mono", "max_piece": [1, 1],
49
+ "remono_from_mode": pg.get("mode"),
50
+ "n_pieces": len(pieces), "n_cells": W * H,
51
+ "pieces": [{"col": c, "row": r, "width": 1, "height": 1, "part_id": pid,
52
+ "color_rgb": [int(v) for v in colors[ci]]}
53
+ for c, r, _w, _h, ci, pid in pieces],
54
+ }
55
+ return img, piece_grid
56
+
57
+
58
+ def main():
59
+ ap = argparse.ArgumentParser(description=__doc__)
60
+ ap.add_argument("--piece-grids", required=True,
61
+ help="glob des piece_grid_*.json source")
62
+ ap.add_argument("--out-dir", required=True)
63
+ ap.add_argument("--limit", type=int, default=None,
64
+ help="ne traiter que les N premiers (ordre trié)")
65
+ a = ap.parse_args()
66
+ out = Path(a.out_dir)
67
+ out.mkdir(parents=True, exist_ok=True)
68
+ paths = sorted(glob.glob(a.piece_grids))[: a.limit]
69
+ for i, jp in enumerate(paths, 1):
70
+ pg = json.load(open(jp))
71
+ uid = Path(jp).stem[len("piece_grid_"):]
72
+ png = out / f"canvas_mosaic_{uid}.png"
73
+ if png.exists(): # resume
74
+ continue
75
+ img, mono = mono_from_piece_grid(pg)
76
+ img.save(png)
77
+ json.dump(mono, open(out / f"piece_grid_{uid}.json", "w"))
78
+ if i % 20 == 0 or i == len(paths):
79
+ print(f"[{i}/{len(paths)}] {uid}")
80
+ print(f"done → {out}")
81
+
82
+
83
+ if __name__ == "__main__":
84
+ main()
code/forge_LAR_2mosaic/wikiart.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Stream wikiart (HuggingFace) → mosaïques LEGO, SANS télécharger le dataset.
3
+
4
+ Tire N images de `huggan/wikiart` à la volée et les passe dans la forge locale →
5
+ `dataset_inputs/canvas_mosaic_XXX.png` + `piece_grid_XXX.json` (prêts pour
6
+ `mosaic2fragments`). Aucun téléchargement complet (~1-2 Mo/image en flux).
7
+
8
+ Exemple :
9
+ python3 forge_LAR_2mosaic/wikiart.py --n 200 --out-dir dataset_inputs --grid 96 --mode plate
10
+ python3 mosaic2fragments/batch.py --inputs dataset_inputs/canvas_mosaic_*.png --out dataset_wikiart
11
+
12
+ Dépendance : `pip install datasets` (HuggingFace). Réseau requis.
13
+ """
14
+ import argparse
15
+ import json
16
+ import uuid
17
+ from itertools import islice
18
+ from pathlib import Path
19
+
20
+ from mosaic import forge_mosaic
21
+
22
+
23
+ def parse_args():
24
+ p = argparse.ArgumentParser(description="wikiart (streaming) -> mosaïques LEGO + GT.")
25
+ p.add_argument("--n", type=int, default=200, help="nb de mosaïques à générer")
26
+ p.add_argument("--skip", type=int, default=0, help="sauter les K premières images du flux")
27
+ p.add_argument("--out-dir", default="dataset_inputs", help="dossier de sortie")
28
+ p.add_argument("--grid", type=int, default=96, help="studs par côté")
29
+ p.add_argument("--stud-size", type=int, default=40, help="px par stud (≥40)")
30
+ p.add_argument("--joint-px", type=int, default=None, help="largeur du joint (défaut ~3)")
31
+ p.add_argument("--mode", choices=["tile", "plate", "brick", "mono"], default="tile",
32
+ help="mono = tuiles 1×1 seules (pour le curriculum ultracompact)")
33
+ p.add_argument("--big-plates", action="store_true", help="réactive 4×8/4×10")
34
+ p.add_argument("--max-dominant-frac", type=float, default=0.55,
35
+ help="garde-fou : rejeter une image si une seule couleur LEGO couvre "
36
+ "> cette fraction des cellules (impressionnistes → aplats monochromes). "
37
+ "1.0 ou plus = désactivé")
38
+ p.add_argument("--dataset", default="huggan/wikiart",
39
+ help="dataset HF en streaming (image attendue dans ex['image'])")
40
+ return p.parse_args()
41
+
42
+
43
+ def main():
44
+ a = parse_args()
45
+ from datasets import load_dataset # import tardif : message clair si absent
46
+ out = Path(a.out_dir)
47
+ out.mkdir(parents=True, exist_ok=True)
48
+ print(f"streaming {a.dataset} (train) → {a.n} mosaïques "
49
+ f"(mode={a.mode}, grid={a.grid}, skip={a.skip})…")
50
+ ds = load_dataset(a.dataset, split="train", streaming=True)
51
+
52
+ made = 0
53
+ rejected = 0 # garde-fou couleur dominante
54
+ for ex in islice(ds, a.skip, None):
55
+ if made >= a.n:
56
+ break
57
+ try:
58
+ img = ex["image"].convert("RGB")
59
+ except Exception as e: # image illisible / champ manquant
60
+ print(f" skip (image illisible): {e}")
61
+ continue
62
+ if min(img.size) < a.grid: # trop petite pour la grille demandée
63
+ continue
64
+ uid = str(uuid.uuid4()) # nom unique, uuid4 canonique (wikiart n'a pas d'ID)
65
+ try:
66
+ mos, grid = forge_mosaic(
67
+ img, grid_w=a.grid, grid_h=a.grid, stud_size=a.stud_size,
68
+ joint_px=a.joint_px, mode=a.mode, big_plates=a.big_plates,
69
+ source_name=uid, max_dominant_frac=a.max_dominant_frac)
70
+ except Exception as e: # forge échoue → on saute l'image
71
+ print(f" skip (forge: {e})")
72
+ continue
73
+ if mos is None: # garde-fou : aplat monochrome → rejeté
74
+ rejected += 1
75
+ continue
76
+ mos.save(out / f"canvas_mosaic_{uid}.png")
77
+ (out / f"piece_grid_{uid}.json").write_text(json.dumps(grid))
78
+ made += 1
79
+ if made % 20 == 0:
80
+ print(f" {made}/{a.n}… (rejetées par garde-fou : {rejected})")
81
+ print(f"Fait : {made} mosaïques dans {out}/ (rejetées par garde-fou couleur : {rejected})")
82
+ print(f"Ensuite : python3 forge_mosaics/mosaic2fragments/batch.py "
83
+ f"--inputs {out}/canvas_mosaic_*.png --out dataset_wikiart")
84
+
85
+
86
+ if __name__ == "__main__":
87
+ main()
code/mosaic2fragments/batch.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Forge multiple mosaic samples by varying random seeds (and optionally inputs).
3
+
4
+ For 50 mosaics with a single input image, this produces 50 distinct
5
+ fragmentations of the same target. To grow real diversity, feed different
6
+ canvas_mosaic.png files via --inputs.
7
+ """
8
+
9
+ import argparse
10
+ from pathlib import Path
11
+
12
+ from forge_dataset import forge_one
13
+ from visualize import visualize
14
+
15
+
16
+ def main():
17
+ p = argparse.ArgumentParser()
18
+ p.add_argument('--inputs', nargs='+', default=['exp1/canvas_mosaic.png'],
19
+ help='One or more canvas_mosaic.png paths')
20
+ p.add_argument('--out', default='dataset',
21
+ help='Root output directory (one subfolder per sample)')
22
+ p.add_argument('--n-samples', type=int, default=5,
23
+ help='Total number of mosaic samples to generate')
24
+ p.add_argument('--seed-start', type=int, default=0)
25
+ p.add_argument('--n-sides-min', type=int, default=16)
26
+ p.add_argument('--n-sides-max', type=int, default=24)
27
+ p.add_argument('--max-area-loss', type=float, default=0.01,
28
+ help="reco B — perte d'aire tolérée pour polygon_n (défaut 1%%) ; "
29
+ "c'est LE budget, n en découle")
30
+ p.add_argument('--n-frag-min', type=int, default=10)
31
+ p.add_argument('--n-frag-max', type=int, default=15)
32
+ p.add_argument('--canvas-w', type=int, default=3500)
33
+ p.add_argument('--canvas-h', type=int, default=3500)
34
+ p.add_argument('--debug', action='store_true',
35
+ help='écrit les fichiers DEBUG (pieces.json + source_yolo_viz.png) ; OFF par défaut')
36
+ p.add_argument('--name-from-input', action='store_true',
37
+ help="Nomme le dossier mosaic_<id> d'après le PNG d'entrée "
38
+ "(canvas_mosaic_<id>.png) au lieu de mosaic_000 séquentiel "
39
+ "→ noms uniques (uuid) préservés en sortie")
40
+ p.add_argument('--no-rotation', action='store_true',
41
+ help='Curriculum L1 : fragments éclatés SANS rotation (translation seule)')
42
+ p.add_argument('--placement', choices=['scatter', 'explode'], default='scatter',
43
+ help='explode = curriculum L0 : vue éclatée (positions relatives gardées)')
44
+ p.add_argument('--frag-distribution', choices=['balanced', 'compact'], default='balanced',
45
+ help='balanced (défaut) ou compact (~rectangulaire, moins de sommets)')
46
+ p.add_argument('--erode-px-min', type=int, default=0)
47
+ p.add_argument('--erode-px-max', type=int, default=0)
48
+ p.add_argument('--holes-min', type=int, default=0)
49
+ p.add_argument('--holes-max', type=int, default=0)
50
+ p.add_argument('--missing-min', type=int, default=0)
51
+ p.add_argument('--missing-max', type=int, default=0)
52
+ args = p.parse_args()
53
+ degrade = {
54
+ 'erode_px': (args.erode_px_min, args.erode_px_max),
55
+ 'holes': (args.holes_min, args.holes_max),
56
+ 'missing': (args.missing_min, args.missing_max),
57
+ }
58
+
59
+ out_root = Path(args.out)
60
+ for i in range(args.n_samples):
61
+ inp = args.inputs[i % len(args.inputs)]
62
+ seed = args.seed_start + i
63
+ if args.name_from_input:
64
+ stem = Path(inp).stem
65
+ uid = stem[len('canvas_mosaic_'):] if stem.startswith('canvas_mosaic_') else stem
66
+ sample_dir = out_root / f'mosaic_{uid}'
67
+ else:
68
+ sample_dir = out_root / f'mosaic_{i:03d}'
69
+ print(f"\n=== sample {i:03d} (seed={seed}, input={inp}) ===")
70
+ forge_one(
71
+ target_path=inp,
72
+ out_dir=sample_dir,
73
+ n_sides_range=(args.n_sides_min, args.n_sides_max),
74
+ max_area_loss=args.max_area_loss,
75
+ n_frag_range=(args.n_frag_min, args.n_frag_max),
76
+ canvas_size=(args.canvas_w, args.canvas_h),
77
+ stud_size=None,
78
+ seed=seed,
79
+ degrade=degrade,
80
+ rotate=not args.no_rotation,
81
+ placement=args.placement,
82
+ frag_distribution=args.frag_distribution,
83
+ debug=args.debug,
84
+ )
85
+ if args.debug:
86
+ visualize(sample_dir)
87
+
88
+
89
+ if __name__ == '__main__':
90
+ main()
code/mosaic2fragments/curriculum.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Curriculum de dégradation — génère les 5 paliers L0→L4 dans des sous-dossiers
3
+ `<out>/L0_explode` … `<out>/L4_strong`, depuis UN MÊME jeu de mosaïques de base.
4
+
5
+ Design **apparié** : même mosaïque + même seed à tous les paliers → la GT
6
+ (fragmentation + arêtes, fixée avant tout tirage de dégradation) est IDENTIQUE
7
+ d'un palier à l'autre ; seule la difficulté de l'INPUT change. → la courbe
8
+ score(difficulté) du GNN se lit à variance faible.
9
+
10
+ Paliers (ladder monotone) :
11
+ L0_explode vue éclatée (positions relatives conservées), sans rotation ← le + facile
12
+ L1_translation scatter aléatoire, sans rotation, aucune dégradation
13
+ L2_rotation scatter + rotation, aucune dégradation
14
+ L3_light scatter + rotation, dégradation LÉGÈRE (érosion 1-2 px, 0-1 trou)
15
+ L4_strong scatter + rotation, dégradation FORTE (érosion 2-6 px, trous, manquants)
16
+
17
+ ⚠️ DAFNE B (distribution de découpe) n'est instrumenté que partiellement, via
18
+ `--frag-distribution` ; DAFNE D (fragments parasites) n'est pas implémenté.
19
+
20
+ Inputs = mosaïques rendues : soit des `canvas_mosaic_*.png`, soit les `target.png`
21
+ d'un dataset clean existant (target.png = copie de la mosaïque d'entrée).
22
+
23
+ Exemples :
24
+ # apparié 1:1 sur les mosaïques wikiart déjà rendues
25
+ python3 forge_mosaics/mosaic2fragments/curriculum.py \
26
+ --inputs-glob 'output/wikiart_inputs/canvas_mosaic_*.png' --out output --jobs 6
27
+
28
+ # augmenter : 5 fragmentations (seeds) par mosaïque → 500/palier à partir de 100 images
29
+ python3 forge_mosaics/mosaic2fragments/curriculum.py \
30
+ --inputs output/wikiart_inputs/canvas_mosaic_*.png --out output --n-per-input 5
31
+
32
+ Puis collate par palier :
33
+ for L in output/L?_*; do python3 forge_mosaics/features/collate.py --dataset "$L"; done
34
+ """
35
+ import argparse
36
+ import glob
37
+ import zlib
38
+ from pathlib import Path
39
+
40
+ from forge_dataset import forge_one
41
+ from visualize import visualize
42
+
43
+ # (placement, rotate, érosion px, trous, fragments manquants) par palier.
44
+ # placement explode = vue éclatée (positions relatives gardées, juste espacées)
45
+ # placement scatter = placement aléatoire (peut échanger les positions)
46
+ LEVELS = {
47
+ "L0_explode": dict(placement="explode", rotate=False, erode=(0, 0), holes=(0, 0), missing=(0, 0)),
48
+ "L1_translation": dict(placement="scatter", rotate=False, erode=(0, 0), holes=(0, 0), missing=(0, 0)),
49
+ "L2_rotation": dict(placement="scatter", rotate=True, erode=(0, 0), holes=(0, 0), missing=(0, 0)),
50
+ "L3_light": dict(placement="scatter", rotate=True, erode=(1, 2), holes=(0, 1), missing=(0, 0)),
51
+ "L4_strong": dict(placement="scatter", rotate=True, erode=(2, 6), holes=(1, 3), missing=(0, 2)), # = degraded actuel
52
+ }
53
+ # L5 « knobs poussés » RETIRÉ (saturait : 0.092 vs 0.088 pour L4). Le vrai durcissement
54
+ # passe par l'axe ORTHOGONAL --frag-distribution {voronoi, clusters} (DAFNE B), pas par
55
+ # plus d'érosion. Structure de sortie = output/<frag-distribution>/<palier>/mosaic_*.
56
+
57
+ FRAG_DISTRIBUTIONS = ["balanced", "compact", "ultracompact", "voronoi", "clusters"]
58
+
59
+
60
+ def input_uid(path):
61
+ """Identifiant stable d'une mosaïque de base (pour apparier les paliers)."""
62
+ p = Path(path)
63
+ if p.stem == "target": # .../mosaic_<uuid>/target.png
64
+ name = p.parent.name
65
+ return name[len("mosaic_"):] if name.startswith("mosaic_") else name
66
+ if p.stem.startswith("canvas_mosaic_"): # canvas_mosaic_<id>.png
67
+ return p.stem[len("canvas_mosaic_"):]
68
+ return p.stem
69
+
70
+
71
+ def parse_args():
72
+ p = argparse.ArgumentParser(description=__doc__,
73
+ formatter_class=argparse.RawDescriptionHelpFormatter)
74
+ p.add_argument("--inputs", nargs="+", default=[],
75
+ help="mosaïques de base (canvas_mosaic_*.png ou target.png d'un dataset clean)")
76
+ p.add_argument("--inputs-glob", default=None,
77
+ help="motif glob résolu en interne (robuste pour des milliers d'entrées, "
78
+ "évite ARG_MAX) ; ex. 'output/wikiart_inputs/canvas_mosaic_*.png'")
79
+ p.add_argument("--out", default="output", help="racine → output/<frag-distribution>/<palier>/")
80
+ p.add_argument("--frag-distribution", choices=FRAG_DISTRIBUTIONS, default="balanced",
81
+ help="motif de découpe (axe orthogonal aux paliers). balanced (défaut), "
82
+ "compact et ultracompact (= compact sur une mosaïque 1×1, cf. "
83
+ "forge_LAR_2mosaic --mode mono) sont implémentés ; voronoi/clusters "
84
+ "(DAFNE B, distribution de tailles continue) = à venir")
85
+ p.add_argument("--n-per-input", type=int, default=1,
86
+ help="nb de fragmentations (seeds) par mosaïque de base (augmentation)")
87
+ p.add_argument("--seed-start", type=int, default=0)
88
+ p.add_argument("--seed-mode", choices=("uid", "constant"), default="uid",
89
+ help="uid (défaut) : seed = crc32(uuid de la mosaïque) + seed-start "
90
+ "→ une découpe DIFFÉRENTE par mosaïque. constant : ancien "
91
+ "comportement (seed = seed-start pour toutes) — à n'utiliser "
92
+ "que pour reproduire un run d'avant le 27/07/2026")
93
+ p.add_argument("--n-sides-min", type=int, default=16)
94
+ p.add_argument("--n-sides-max", type=int, default=24)
95
+ p.add_argument("--n-frag-min", type=int, default=10)
96
+ p.add_argument("--n-frag-max", type=int, default=15)
97
+ p.add_argument("--max-area-loss", type=float, default=0.01,
98
+ help="reco B — fraction d'aire que polygon_n a le droit de PERDRE "
99
+ "vs polygon_raw (défaut 0.01 = 1 %%). C'est LE budget ; le "
100
+ "nombre de sommets en découle (correctif 23/07/2026).")
101
+ p.add_argument("--missing-max", type=int, default=None,
102
+ help="plafond du nb de fragments MANQUANTS (DAFNE C) des paliers. "
103
+ "DAFNE C est un POURCENTAGE, notre `missing` un COMPTE ABSOLU → "
104
+ "défaut = round(0.15·n_frag_max) (~15 %% de k, quel que soit k). "
105
+ "À k=10-15 ça donne 2 = le réglage historique exact (run 25k "
106
+ "reproductible) ; à k=2/3 → 0 ; k=5 → 1. Passer une valeur pour "
107
+ "outrepasser.")
108
+ p.add_argument("--canvas-w", type=int, default=4096)
109
+ p.add_argument("--canvas-h", type=int, default=4096)
110
+ p.add_argument("--levels", nargs="+", default=list(LEVELS),
111
+ help=f"sous-ensemble de paliers (défaut : tous → {list(LEVELS)})")
112
+ p.add_argument("--jobs", type=int, default=1,
113
+ help="processus parallèles (1 = série). Forge = CPU-bound, embarrassingly "
114
+ "parallel. Sur machine partagée : plafonner (ex. 12 sur 24), pas tous les cœurs")
115
+ p.add_argument("--debug", action="store_true",
116
+ help="écrit les fichiers DEBUG (pieces.json + source_yolo_viz.png), "
117
+ "lus nulle part par l'entraînement ; OFF par défaut")
118
+ return p.parse_args()
119
+
120
+
121
+ def _run_task(t):
122
+ """Worker (1 instance). Top-level → picklable par multiprocessing (spawn macOS).
123
+
124
+ ROBUSTESSE (grosses générations) :
125
+ - **resume** : si l'instance est déjà complète (`degradation.md` = dernier fichier
126
+ écrit), on la saute → un relancement reprend où ça s'est arrêté.
127
+ - **tolérance** : toute exception d'une instance est CAPTURÉE et renvoyée comme
128
+ `FAIL …` au lieu de planter tout le batch (1 mosaïque pourrie ≠ 25 000 perdues).
129
+ """
130
+ if (Path(t["dir"]) / "degradation.md").exists():
131
+ return f"skip {t['label']}"
132
+ try:
133
+ forge_one(
134
+ target_path=t["inp"], out_dir=t["dir"],
135
+ n_sides_range=t["n_sides"], n_frag_range=t["n_frag"], canvas_size=t["canvas"],
136
+ stud_size=None, seed=t["seed"], degrade=t["degrade"],
137
+ rotate=t["rotate"], placement=t["placement"], frag_distribution=t["frag_distribution"],
138
+ debug=t["debug"], max_area_loss=t["max_area_loss"],
139
+ )
140
+ if t["viz"]:
141
+ visualize(t["dir"])
142
+ return t["label"]
143
+ except Exception as e:
144
+ return f"FAIL {t['label']}: {type(e).__name__}: {e}"
145
+
146
+
147
+ def main():
148
+ a = parse_args()
149
+ if a.frag_distribution in ("voronoi", "clusters"):
150
+ raise SystemExit(f"--frag-distribution {a.frag_distribution} : pas encore "
151
+ "implémenté (DAFNE B à venir ; dispo : balanced, compact)")
152
+ inputs = list(a.inputs) + (sorted(glob.glob(a.inputs_glob)) if a.inputs_glob else [])
153
+ if not inputs:
154
+ raise SystemExit("aucune entrée : fournir --inputs ... ou --inputs-glob 'motif'")
155
+ out_root = Path(a.out) / a.frag_distribution
156
+ tasks = []
157
+ for inp in inputs:
158
+ uid = input_uid(inp)
159
+ for s in range(a.n_per_input):
160
+ # ⚠️ Le seed DOIT dépendre de la mosaïque. Avec un seed constant, en
161
+ # `mono` (tuiles 1×1) la grille d'adjacence est identique pour toute
162
+ # image → la fragmentation, déterministe, rendait la MÊME découpe et
163
+ # les MÊMES poses pour les 5000 mosaïques (bug trouvé le 27/07/2026 :
164
+ # les 4 datasets mono_compact publiés n'avaient qu'une seule
165
+ # géométrie). En `poly` le bug était masqué : la découpe suit les
166
+ # joints de tuiles variables, qui dépendent de l'image.
167
+ # crc32(uid) ne dépend QUE de la mosaïque → l'appariement reste
168
+ # exact entre paliers ET entre valeurs de k.
169
+ seed = (zlib.crc32(uid.encode()) + a.seed_start + s) % (2 ** 31) \
170
+ if a.seed_mode == "uid" else a.seed_start + s
171
+ # même seed sur tous les paliers → mosaïque/fragmentation appariée
172
+ suffix = f"_s{seed}" if a.n_per_input > 1 else ""
173
+ for level in a.levels:
174
+ cfg = LEVELS[level]
175
+ # DAFNE C est un %, `missing` un compte absolu → plafond ~15 % de k.
176
+ # round(0.15·15)=2 ⟹ identique au réglage historique à k=10-15.
177
+ cap = a.missing_max if a.missing_max is not None \
178
+ else round(0.15 * a.n_frag_max)
179
+ miss = (min(cfg["missing"][0], cap), min(cfg["missing"][1], cap))
180
+ tasks.append(dict(
181
+ inp=inp, dir=str(out_root / level / f"mosaic_{uid}{suffix}"),
182
+ n_sides=(a.n_sides_min, a.n_sides_max),
183
+ n_frag=(a.n_frag_min, a.n_frag_max),
184
+ canvas=(a.canvas_w, a.canvas_h), seed=seed,
185
+ degrade={"erode_px": cfg["erode"], "holes": cfg["holes"], "missing": miss},
186
+ rotate=cfg["rotate"], placement=cfg["placement"],
187
+ frag_distribution=a.frag_distribution, viz=a.debug, debug=a.debug,
188
+ max_area_loss=a.max_area_loss,
189
+ label=f"{level} mosaic_{uid}{suffix}"))
190
+ total = len(tasks)
191
+ print(f"curriculum [{a.frag_distribution}] : {total} instances → {out_root}/ (jobs={a.jobs})")
192
+ fails = skips = 0
193
+
194
+ def _tally(lab, i):
195
+ nonlocal fails, skips
196
+ if lab.startswith("FAIL"):
197
+ fails += 1
198
+ elif lab.startswith("skip"):
199
+ skips += 1
200
+ if lab.startswith("FAIL") or i % 100 == 0 or i == total:
201
+ print(f"[{i}/{total}] {lab}")
202
+
203
+ if a.jobs <= 1:
204
+ for i, t in enumerate(tasks, 1):
205
+ _tally(_run_task(t), i)
206
+ else:
207
+ import multiprocessing as mp
208
+ with mp.Pool(a.jobs) as pool:
209
+ for i, lab in enumerate(pool.imap_unordered(_run_task, tasks), 1):
210
+ _tally(lab, i)
211
+ print(f"\nFait : {total - fails - skips} générées, {skips} sautées (resume), {fails} échecs.")
212
+ print(f"Collate par palier :\n"
213
+ f" for L in {out_root}/L*_*; do python3 forge_mosaics/features/collate.py --dataset \"$L\"; done")
214
+
215
+
216
+ if __name__ == "__main__":
217
+ main()
code/mosaic2fragments/forge_dataset.py ADDED
@@ -0,0 +1,1161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Forge a LEGO mosaic dataset for YOLO + GNN training.
3
+
4
+ Inputs: a canvas_mosaic.png produced by ../forge_LAR_2mosaic/ (square, >=40 px per
5
+ stud, grey joints, LEGO palette without greys).
6
+ Outputs (per mosaic, in <out_dir>/mosaic_XXX/):
7
+ target.png — copy of the input mosaic
8
+ source.png — fragments exploded on a white canvas (YOLO-Seg input)
9
+ source_yolo.txt — YOLO-Seg polygons, one line per fragment (THE YOLO ground truth)
10
+ pieces.json — detected LEGO pieces (debug only, read nowhere) — opt-in via --debug
11
+ graph_complete.json — N nodes (fragment features) + adjacency edges (target)
12
+ graph_fragments.json — same N nodes, zero edges (GNN input)
13
+ gt_layout.json — exact footprint and pose (x, y, rot) of each fragment
14
+ degradation.md — degradation report (empty means clean)
15
+ fragments/frag_XX.png — per-fragment alpha crop in target frame
16
+
17
+ Pipeline:
18
+ 1. Joint detection on the rendered mosaic → LEGO piece layout
19
+ 2. Union-find on cells → pieces (rectangles on the stud grid)
20
+ 3. Piece adjacency graph → region-growing fragmentation (k ∈ [10,15] by default)
21
+ 4. Per-fragment polygon → simplified under an AREA-LOSS budget (--max-area-loss,
22
+ default 1%), the vertex count being an output, not a target
23
+ 5. Per-fragment features (global) + per-side features
24
+ 6. Fragment adjacency = boundary segments shared between fragments
25
+ 7. Random placement of rotated fragments on a white canvas (axes-aligned + ±5°)
26
+ 8. Polygon export in YOLO-Seg format (normalized)
27
+ """
28
+
29
+ import argparse
30
+ import collections
31
+ import heapq
32
+ import json
33
+ import os
34
+ import random
35
+ import sys
36
+ from pathlib import Path
37
+
38
+ import cv2
39
+ import networkx as nx
40
+ import numpy as np
41
+ from PIL import Image
42
+
43
+ # Extraction de features = module PARTAGÉ post-YOLO/pré-GNN (features/), importé
44
+ # depuis la racine du repo → forge synthétique et future chaîne YOLO utilisent le
45
+ # MÊME code (alignement de schéma garanti).
46
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
47
+ from features.fragment_features import ( # noqa: E402
48
+ _polygon_signed_area, extract_polygon, resample_reflex_aware,
49
+ pca_canonical_rotation, compute_fragment_features, MAX_AREA_LOSS_DEFAULT,
50
+ )
51
+
52
+
53
+ # ============================================================
54
+ # 1. Joint detection
55
+ # ============================================================
56
+
57
+ def is_joint_pixel(px, target=136, tol=35):
58
+ r, g, b = int(px[0]), int(px[1]), int(px[2])
59
+ if abs(r - target) > tol or abs(g - target) > tol or abs(b - target) > tol:
60
+ return False
61
+ if max(r, g, b) - min(r, g, b) > 25:
62
+ return False
63
+ return True
64
+
65
+
66
+ def _cell_is_gray(img, i, j, stud_size):
67
+ """True if the interior of cell (i, j) is itself joint-gray (= a gray piece)."""
68
+ cy = min(j * stud_size + stud_size // 2, img.shape[0] - 1)
69
+ cx = min(i * stud_size + stud_size // 2, img.shape[1] - 1)
70
+ return is_joint_pixel(img[cy, cx])
71
+
72
+
73
+ def detect_joints(img, stud_size, tolerate_gray=True):
74
+ """Return joint_v[i, j] (vertical joints) and joint_h[i, j] (horizontal joints).
75
+
76
+ joint_v[i, j] = True iff there is a joint between cell (i, j) and (i+1, j).
77
+ joint_h[i, j] = True iff there is a joint between cell (i, j) and (i, j+1).
78
+ Convention: i = column index (x-axis), j = row index (y-axis).
79
+
80
+ With tolerate_gray=True, a gray boundary is NOT a joint when BOTH adjacent
81
+ cell interiors are themselves gray — we are inside a gray LEGO piece, not on
82
+ a real joint. This lets gray pieces stay in the palette. The only
83
+ unresolvable case is two *different* gray pieces sharing a gray joint (rare,
84
+ accepted). For mosaics generated without gray pieces this is a strict no-op.
85
+ """
86
+ H, W = img.shape[:2]
87
+ n_cols = W // stud_size
88
+ n_rows = H // stud_size
89
+
90
+ joint_v = np.zeros((n_cols - 1, n_rows), dtype=bool)
91
+ joint_h = np.zeros((n_cols, n_rows - 1), dtype=bool)
92
+
93
+ for i in range(n_cols - 1):
94
+ x = (i + 1) * stud_size
95
+ for j in range(n_rows):
96
+ y_mid = j * stud_size + stud_size // 2
97
+ samples = [
98
+ is_joint_pixel(img[j * stud_size + stud_size // 4, x]),
99
+ is_joint_pixel(img[y_mid, x]),
100
+ is_joint_pixel(img[j * stud_size + 3 * stud_size // 4, x]),
101
+ ]
102
+ is_joint = sum(samples) >= 2
103
+ if (is_joint and tolerate_gray
104
+ and _cell_is_gray(img, i, j, stud_size)
105
+ and _cell_is_gray(img, i + 1, j, stud_size)):
106
+ is_joint = False # interior of a gray piece, not a joint
107
+ joint_v[i, j] = is_joint
108
+
109
+ for j in range(n_rows - 1):
110
+ y = (j + 1) * stud_size
111
+ for i in range(n_cols):
112
+ x_mid = i * stud_size + stud_size // 2
113
+ samples = [
114
+ is_joint_pixel(img[y, i * stud_size + stud_size // 4]),
115
+ is_joint_pixel(img[y, x_mid]),
116
+ is_joint_pixel(img[y, i * stud_size + 3 * stud_size // 4]),
117
+ ]
118
+ is_joint = sum(samples) >= 2
119
+ if (is_joint and tolerate_gray
120
+ and _cell_is_gray(img, i, j, stud_size)
121
+ and _cell_is_gray(img, i, j + 1, stud_size)):
122
+ is_joint = False
123
+ joint_h[i, j] = is_joint
124
+
125
+ return joint_v, joint_h
126
+
127
+
128
+ # ============================================================
129
+ # 2. Piece detection via union-find on cells
130
+ # ============================================================
131
+
132
+ def detect_pieces(img, stud_size):
133
+ joint_v, joint_h = detect_joints(img, stud_size)
134
+ n_cols = joint_v.shape[0] + 1
135
+ n_rows = joint_h.shape[1] + 1
136
+
137
+ parent = {(i, j): (i, j) for i in range(n_cols) for j in range(n_rows)}
138
+
139
+ def find(c):
140
+ while parent[c] != c:
141
+ parent[c] = parent[parent[c]]
142
+ c = parent[c]
143
+ return c
144
+
145
+ def union(a, b):
146
+ ra, rb = find(a), find(b)
147
+ if ra != rb:
148
+ parent[ra] = rb
149
+
150
+ for i in range(n_cols - 1):
151
+ for j in range(n_rows):
152
+ if not joint_v[i, j]:
153
+ union((i, j), (i + 1, j))
154
+ for i in range(n_cols):
155
+ for j in range(n_rows - 1):
156
+ if not joint_h[i, j]:
157
+ union((i, j), (i, j + 1))
158
+
159
+ groups = collections.defaultdict(list)
160
+ for c in parent:
161
+ groups[find(c)].append(c)
162
+
163
+ pieces = []
164
+ for cells in groups.values():
165
+ cells = sorted(cells)
166
+ i_min = min(c[0] for c in cells)
167
+ i_max = max(c[0] for c in cells)
168
+ j_min = min(c[1] for c in cells)
169
+ j_max = max(c[1] for c in cells)
170
+ # Sample interior color from the center of an interior cell
171
+ ci, cj = cells[len(cells) // 2]
172
+ cx = ci * stud_size + stud_size // 2
173
+ cy = cj * stud_size + stud_size // 2
174
+ color = img[cy, cx][:3].tolist()
175
+ pieces.append({
176
+ 'cells': cells,
177
+ 'bbox_grid': [i_min, j_min, i_max - i_min + 1, j_max - j_min + 1],
178
+ 'color': [int(c) for c in color],
179
+ })
180
+ return pieces
181
+
182
+
183
+ # ============================================================
184
+ # 2b. Sanity checks on detected pieces
185
+ # ============================================================
186
+
187
+ def sanity_check_pieces(pieces, n_cols, n_rows):
188
+ """Return a list of warning strings if detected pieces look suspicious.
189
+
190
+ Checks:
191
+ - all grid cells are covered exactly once
192
+ - every piece is rectangular (its cells fill its bbox)
193
+ - share of 1x1 pieces is not abnormally high (a tell-tale sign of
194
+ gray-tile false-positive joints, since gray pieces get internally
195
+ split into 1x1s if joint detection is over-aggressive)
196
+ """
197
+ warnings = []
198
+ total = sum(len(p['cells']) for p in pieces)
199
+ expected = n_cols * n_rows
200
+ if total != expected:
201
+ warnings.append(f"cell coverage: {total} from pieces, expected {expected}")
202
+
203
+ seen = set()
204
+ dup = 0
205
+ for p in pieces:
206
+ for c in p['cells']:
207
+ if c in seen:
208
+ dup += 1
209
+ seen.add(c)
210
+ if dup:
211
+ warnings.append(f"{dup} cells assigned to multiple pieces")
212
+
213
+ non_rect = 0
214
+ for p in pieces:
215
+ cells = p['cells']
216
+ i_min = min(c[0] for c in cells)
217
+ i_max = max(c[0] for c in cells)
218
+ j_min = min(c[1] for c in cells)
219
+ j_max = max(c[1] for c in cells)
220
+ if len(cells) != (i_max - i_min + 1) * (j_max - j_min + 1):
221
+ non_rect += 1
222
+ if non_rect:
223
+ warnings.append(f"{non_rect}/{len(pieces)} pieces are non-rectangular "
224
+ "(joint detection inconsistency)")
225
+
226
+ n_1x1 = sum(1 for p in pieces if len(p['cells']) == 1)
227
+ pct_1x1 = 100.0 * n_1x1 / max(len(pieces), 1)
228
+ if pct_1x1 > 60.0:
229
+ warnings.append(
230
+ f"{pct_1x1:.0f}% of pieces are 1x1 ({n_1x1}/{len(pieces)}). "
231
+ "Anything above ~60% suggests joint over-detection."
232
+ )
233
+
234
+ # Targeted gray-tile check: a large cluster of 1x1 with a similar near-gray
235
+ # color is the smoking gun for Light/Dark Bluish Gray false positives.
236
+ gray_1x1 = []
237
+ for p in pieces:
238
+ if len(p['cells']) != 1:
239
+ continue
240
+ r, g, b = p['color']
241
+ if (max(r, g, b) - min(r, g, b) < 25
242
+ and 80 <= (r + g + b) / 3 <= 200):
243
+ gray_1x1.append(p)
244
+ if len(gray_1x1) > 30:
245
+ warnings.append(
246
+ f"{len(gray_1x1)} gray-ish 1x1 pieces detected — likely "
247
+ "Light Bluish Gray / Dark Bluish Gray / Flat Silver / "
248
+ "Pearl Light Gray / Metallic Silver tiles being mistaken "
249
+ "for joints. Disable those colors in the palette."
250
+ )
251
+ return warnings
252
+
253
+
254
+ # ============================================================
255
+ # 3. Piece adjacency graph
256
+ # ============================================================
257
+
258
+ def build_piece_graph(pieces):
259
+ cell_to_pid = {}
260
+ for pid, p in enumerate(pieces):
261
+ for cell in p['cells']:
262
+ cell_to_pid[cell] = pid
263
+
264
+ g = nx.Graph()
265
+ for pid in range(len(pieces)):
266
+ g.add_node(pid)
267
+ for cell, pid in cell_to_pid.items():
268
+ i, j = cell
269
+ for di, dj in [(1, 0), (0, 1)]:
270
+ neighbor = (i + di, j + dj)
271
+ if neighbor in cell_to_pid:
272
+ pid2 = cell_to_pid[neighbor]
273
+ if pid != pid2:
274
+ g.add_edge(pid, pid2)
275
+ return g
276
+
277
+
278
+ # ============================================================
279
+ # 4. Fragmentation by balanced region growing
280
+ # ============================================================
281
+
282
+ def _bfs_distances(piece_graph, source, dist=None):
283
+ """Unweighted shortest-path distances from `source` over `piece_graph`.
284
+ If `dist` is provided, distances are updated only where shorter."""
285
+ if dist is None:
286
+ dist = {n: float('inf') for n in piece_graph.nodes}
287
+ dist[source] = 0
288
+ queue = collections.deque([source])
289
+ while queue:
290
+ u = queue.popleft()
291
+ for v in piece_graph.neighbors(u):
292
+ if dist[u] + 1 < dist[v]:
293
+ dist[v] = dist[u] + 1
294
+ queue.append(v)
295
+ return dist
296
+
297
+
298
+ def select_seeds_farthest(piece_graph, k):
299
+ """Farthest-point sampling: each new seed maximises distance to the nearest existing seed."""
300
+ nodes = list(piece_graph.nodes)
301
+ first = random.choice(nodes)
302
+ seeds = [first]
303
+ dist = _bfs_distances(piece_graph, first)
304
+ while len(seeds) < k:
305
+ # Argmax over nodes; ties broken randomly to avoid bias.
306
+ max_d = max(dist.values())
307
+ candidates = [n for n, d in dist.items() if d == max_d]
308
+ nxt = random.choice(candidates)
309
+ seeds.append(nxt)
310
+ # Update distance-to-nearest-seed by running BFS from new seed.
311
+ _bfs_distances(piece_graph, nxt, dist)
312
+ return seeds
313
+
314
+
315
+ def fragment_pieces(piece_graph, k):
316
+ """Balanced multi-source region growing.
317
+
318
+ Seeds are picked via farthest-point sampling (k-center). At each step the
319
+ currently smallest fragment expands by one queued node — ensuring balanced
320
+ fragment sizes regardless of local connectivity differences.
321
+ """
322
+ nodes = list(piece_graph.nodes)
323
+ if k >= len(nodes):
324
+ return {n: i for i, n in enumerate(nodes)}
325
+
326
+ seeds = select_seeds_farthest(piece_graph, k)
327
+ assigned = {s: i for i, s in enumerate(seeds)}
328
+ frontier = [collections.deque([s]) for s in seeds]
329
+ sizes = [1] * k
330
+
331
+ # Min-heap keyed on (current size, fragment_id) → smallest grows first.
332
+ # Tie-breaker is fragment_id which is stable.
333
+ heap = [(1, i) for i in range(k)]
334
+ heapq.heapify(heap)
335
+
336
+ while heap:
337
+ _, fid = heapq.heappop(heap)
338
+ if not frontier[fid]:
339
+ continue
340
+ current = frontier[fid].popleft()
341
+ for neighbor in piece_graph.neighbors(current):
342
+ if neighbor not in assigned:
343
+ assigned[neighbor] = fid
344
+ frontier[fid].append(neighbor)
345
+ sizes[fid] += 1
346
+ if frontier[fid]:
347
+ heapq.heappush(heap, (sizes[fid], fid))
348
+ return assigned
349
+
350
+
351
+ def fragment_pieces_compact(piece_graph, pieces, k):
352
+ """Region growing biaisé COMPACITÉ — `--frag-distribution compact`.
353
+
354
+ Comme fragment_pieces, mais à chaque pas le fragment ajoute la pièce-frontière
355
+ qui **maximise le remplissage de sa bbox** (cellules remplies / aire bbox) →
356
+ fragments ~rectangulaires, silhouettes régulières, MOINS de coins concaves
357
+ → `n_max` plus petit. On ne coupe JAMAIS une pièce (les bords suivent les
358
+ joints) : donc pas de rectangles parfaits à 4 sommets, le signal de bord pour
359
+ l'appariement GNN survit. **N'altère NI reco-B (⊆ raw) NI le pad+masque** :
360
+ seule la partition change ; le reste du pipeline est identique à balanced.
361
+ """
362
+ nodes = list(piece_graph.nodes)
363
+ if k >= len(nodes):
364
+ return {n: i for i, n in enumerate(nodes)}
365
+
366
+ # Géométrie par pièce : cellules (set de (i,j)) + périmètre propre (rectangle).
367
+ pcells = [set(map(tuple, pieces[p]['cells'])) for p in range(len(pieces))]
368
+ pperim = [2 * (pieces[p]['bbox_grid'][2] + pieces[p]['bbox_grid'][3])
369
+ for p in range(len(pieces))]
370
+
371
+ seeds = select_seeds_farthest(piece_graph, k)
372
+ assigned = {s: i for i, s in enumerate(seeds)}
373
+ frag_cells = [set(pcells[s]) for s in seeds] # cellules par fragment
374
+ sizes = [1] * k
375
+ frontier = [set(n for n in piece_graph.neighbors(s) if n not in assigned)
376
+ for s in seeds]
377
+
378
+ heap = [(1, i) for i in range(k)]
379
+ heapq.heapify(heap)
380
+ while heap:
381
+ _, fid = heapq.heappop(heap)
382
+ cand = [p for p in frontier[fid] if p not in assigned]
383
+ frontier[fid] = set(cand)
384
+ if not cand:
385
+ continue
386
+ fc = frag_cells[fid]
387
+
388
+ def delta_perim(p):
389
+ # Δpérimètre en ajoutant p = périmètre propre de p − 2×(arêtes partagées
390
+ # avec le fragment). Remplir une concavité → Δ négatif → bord plus lisse
391
+ # → moins de coins concaves → reco-B sort moins de sommets.
392
+ shared = 0
393
+ for (i, j) in pcells[p]:
394
+ shared += ((i + 1, j) in fc) + ((i - 1, j) in fc) \
395
+ + ((i, j + 1) in fc) + ((i, j - 1) in fc)
396
+ return (pperim[p] - 2 * shared, -shared, len(pcells[p]))
397
+
398
+ best = min(cand, key=delta_perim) # pièce qui lisse le plus le bord
399
+ assigned[best] = fid
400
+ frag_cells[fid] |= pcells[best]
401
+ sizes[fid] += 1
402
+ frontier[fid].discard(best)
403
+ for nb in piece_graph.neighbors(best):
404
+ if nb not in assigned:
405
+ frontier[fid].add(nb)
406
+ heapq.heappush(heap, (sizes[fid], fid))
407
+
408
+ # composantes non atteintes (rare : graphe normalement connexe) → rattachées
409
+ changed = True
410
+ while changed:
411
+ changed = False
412
+ for n in nodes:
413
+ if n in assigned:
414
+ continue
415
+ nbf = [assigned[x] for x in piece_graph.neighbors(n) if x in assigned]
416
+ if nbf:
417
+ assigned[n] = nbf[0]
418
+ changed = True
419
+ for i, n in enumerate(nodes): # tout isolé restant → fragment propre
420
+ assigned.setdefault(n, k + i)
421
+ return assigned
422
+
423
+
424
+ # ============================================================
425
+ # 5. Fragment polygon and resampling
426
+ # ============================================================
427
+
428
+ def fragment_mask(fragment_cells, img_shape, stud_size):
429
+ H, W = img_shape[:2]
430
+ mask = np.zeros((H, W), dtype=np.uint8)
431
+ for (i, j) in fragment_cells:
432
+ x0, y0 = i * stud_size, j * stud_size
433
+ mask[y0:y0 + stud_size, x0:x0 + stud_size] = 1
434
+ return mask
435
+
436
+
437
+ # extract_polygon, resample_reflex_aware (+ helpers PCA), compute_fragment_features
438
+ # → déplacés dans features/fragment_features.py (module partagé), importés en tête.
439
+ # (resample_polygon équidistant supprimé : remplacé par resample_reflex_aware.)
440
+
441
+
442
+ # ============================================================
443
+ # 7. Fragment adjacencies (segments shared between fragments)
444
+ # ============================================================
445
+
446
+ def compute_fragment_adjacencies(pieces, piece_to_frag, stud_size):
447
+ cell_to_frag = {}
448
+ for pid, p in enumerate(pieces):
449
+ fid = piece_to_frag[pid]
450
+ for cell in p['cells']:
451
+ cell_to_frag[cell] = fid
452
+
453
+ adj = collections.defaultdict(list)
454
+ for cell, fid in cell_to_frag.items():
455
+ i, j = cell
456
+ right = (i + 1, j)
457
+ if right in cell_to_frag and cell_to_frag[right] != fid:
458
+ other = cell_to_frag[right]
459
+ a, b = min(fid, other), max(fid, other)
460
+ x = (i + 1) * stud_size
461
+ adj[(a, b)].append((x, j * stud_size, x, (j + 1) * stud_size))
462
+ bottom = (i, j + 1)
463
+ if bottom in cell_to_frag and cell_to_frag[bottom] != fid:
464
+ other = cell_to_frag[bottom]
465
+ a, b = min(fid, other), max(fid, other)
466
+ y = (j + 1) * stud_size
467
+ adj[(a, b)].append((i * stud_size, y, (i + 1) * stud_size, y))
468
+ return adj, cell_to_frag
469
+
470
+
471
+ def find_outer_fragments_per_side(polygon_n, centroid, frag_id, cell_to_frag,
472
+ stud_size, offset=6, n_samples=7):
473
+ """For each side of polygon_n, vote over multiple samples along the side
474
+ to find the most common adjacent fragment (or None if image edge)."""
475
+ out = []
476
+ n = len(polygon_n)
477
+ for i in range(n):
478
+ p0, p1 = polygon_n[i], polygon_n[(i + 1) % n]
479
+ votes = collections.Counter()
480
+ for t in np.linspace(0.15, 0.85, n_samples):
481
+ sample = (1 - t) * p0 + t * p1
482
+ outward = sample - centroid
483
+ norm = float(np.linalg.norm(outward))
484
+ if norm < 1e-6:
485
+ continue
486
+ outer = sample + outward / norm * offset
487
+ ci, cj = int(outer[0] // stud_size), int(outer[1] // stud_size)
488
+ if (ci, cj) in cell_to_frag:
489
+ o = cell_to_frag[(ci, cj)]
490
+ if o != frag_id:
491
+ votes[o] += 1
492
+ if votes:
493
+ best, _ = votes.most_common(1)[0]
494
+ out.append(int(best))
495
+ else:
496
+ out.append(None)
497
+ return out
498
+
499
+
500
+ # ============================================================
501
+ # 8. Exploded image: cut + rotate + place
502
+ # ============================================================
503
+
504
+ def _disk(radius):
505
+ d = 2 * int(radius) + 1
506
+ return cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (d, d))
507
+
508
+
509
+ def degrade_mask(mask, erode_px=0, n_holes=0, stud_size=40, max_hole_area_frac=0.10):
510
+ """Degraded copy of a fragment alpha mask — only ever REMOVES material, so
511
+ degraded ⊆ perfect (keeps the "area never gained" invariant).
512
+
513
+ erode_px : morphological erosion radius in px (boundary wear).
514
+ n_holes : interior holes punched (missing tesselae *inside*).
515
+ max_hole_area_frac : hard cap on TOTAL hole area (default 10% of the
516
+ post-erosion fragment area). The n_holes disks share
517
+ this budget, so holes never remove more than the cap
518
+ (overlaps / boundary clipping only reduce it further).
519
+ Uses the module RNG (seeded in forge_one) for reproducibility.
520
+ """
521
+ m = (mask > 0).astype(np.uint8)
522
+ if erode_px > 0:
523
+ m = cv2.erode(m, _disk(erode_px))
524
+ if n_holes > 0:
525
+ ys, xs = np.where(m > 0)
526
+ area = len(xs)
527
+ if area:
528
+ budget = max_hole_area_frac * area # ≤10% of fragment area
529
+ r = max(1, int(np.sqrt(budget / (n_holes * np.pi))))
530
+ for _ in range(n_holes):
531
+ k = random.randint(0, area - 1)
532
+ cv2.circle(m, (int(xs[k]), int(ys[k])), r, 0, -1)
533
+ return m
534
+
535
+
536
+ def make_fragment_rgba(fragment_cells, target_img, stud_size, mask=None):
537
+ if mask is None:
538
+ mask = fragment_mask(fragment_cells, target_img.shape, stud_size)
539
+ mask = (mask > 0).astype(np.uint8)
540
+ ys, xs = np.where(mask > 0)
541
+ y_min, y_max = int(ys.min()), int(ys.max())
542
+ x_min, x_max = int(xs.min()), int(xs.max())
543
+ crop = target_img[y_min:y_max + 1, x_min:x_max + 1]
544
+ crop_mask = mask[y_min:y_max + 1, x_min:x_max + 1]
545
+ rgba = np.dstack([crop, crop_mask * 255]).astype(np.uint8)
546
+ return rgba, (x_min, y_min, x_max, y_max)
547
+
548
+
549
+ def rotate_rgba(rgba, angle):
550
+ pil = Image.fromarray(rgba, 'RGBA')
551
+ rot = pil.rotate(angle, resample=Image.BILINEAR, expand=True)
552
+ return np.array(rot)
553
+
554
+
555
+ def _collides(x, y, alpha, occupied):
556
+ """True if fragment alpha placed at (x, y) overlaps any occupied mask."""
557
+ h, w = alpha.shape
558
+ for (ox, oy, omask) in occupied:
559
+ oh, ow = omask.shape
560
+ ix1, iy1 = max(x, ox), max(y, oy)
561
+ ix2, iy2 = min(x + w, ox + ow), min(y + h, oy + oh)
562
+ if ix1 >= ix2 or iy1 >= iy2:
563
+ continue
564
+ a = alpha[iy1 - y:iy2 - y, ix1 - x:ix2 - x]
565
+ b = omask[iy1 - oy:iy2 - oy, ix1 - ox:ix2 - ox]
566
+ if np.logical_and(a, b).any():
567
+ return True
568
+ return False
569
+
570
+
571
+ def _scan_free_position(alpha, occupied, cw, ch, padding, step):
572
+ """Deterministic raster scan for the first non-overlapping top-left position.
573
+ Returns None only if no free spot exists anywhere on the current canvas."""
574
+ h, w = alpha.shape
575
+ y = padding
576
+ while y + h + padding <= ch:
577
+ x = padding
578
+ while x + w + padding <= cw:
579
+ if not _collides(x, y, alpha, occupied):
580
+ return x, y
581
+ x += step
582
+ y += step
583
+ return None
584
+
585
+
586
+ def explode_fragments(fragments_data, target_size, base_factor=1.8, padding=4,
587
+ max_factor=4.0, step=0.3):
588
+ """Placement « vue éclatée » — curriculum L0.
589
+
590
+ Chaque fragment GARDE sa position RELATIVE dans la mosaïque, simplement
591
+ écarté de ses voisins (≈ schéma de montage éclaté). Contrairement au scatter
592
+ aléatoire (place_fragments), aucun échange de position : un fragment du coin
593
+ haut-gauche reste en haut-gauche. On dilate les centroïdes-cible par un
594
+ facteur autour du centre, en l'augmentant jusqu'à supprimer les
595
+ chevauchements. Renvoie (canvas, placements en ordre d'entrée, taille).
596
+ """
597
+ W, H = target_size
598
+ fac = base_factor
599
+ while True:
600
+ cw, ch = int(round(W * fac)), int(round(H * fac))
601
+ cxt, cyt, cxc, cyc = W / 2.0, H / 2.0, cw / 2.0, ch / 2.0
602
+ placements, occupied, overlap = [], [], False
603
+ for f in fragments_data:
604
+ rgba = f['rgba_rotated']
605
+ h, w = rgba.shape[:2]
606
+ alpha = rgba[..., 3] > 0
607
+ x0, y0, x1, y1 = f['bbox_in_target']
608
+ x = int(round(cxc + fac * ((x0 + x1) / 2.0 - cxt) - w / 2.0))
609
+ y = int(round(cyc + fac * ((y0 + y1) / 2.0 - cyt) - h / 2.0))
610
+ x = max(padding, min(x, cw - w - padding))
611
+ y = max(padding, min(y, ch - h - padding))
612
+ if _collides(x, y, alpha, occupied):
613
+ overlap = True
614
+ placements.append({'x': x, 'y': y, 'w': w, 'h': h})
615
+ occupied.append((x, y, alpha))
616
+ if not overlap or fac >= max_factor:
617
+ break
618
+ fac += step
619
+ canvas = Image.new('RGB', (cw, ch), (255, 255, 255))
620
+ for f, place in zip(fragments_data, placements):
621
+ pil = Image.fromarray(f['rgba_rotated'], 'RGBA')
622
+ canvas.paste(pil, (place['x'], place['y']), pil)
623
+ return canvas, placements, (cw, ch)
624
+
625
+
626
+ def place_fragments(fragments_data, canvas_size, max_tries=200, padding=4):
627
+ """Scatter fragments on a white canvas WITHOUT overlap.
628
+
629
+ Per fragment (largest first): (1) random search, to keep the scattered look;
630
+ (2) deterministic raster scan — guaranteed to find a free spot if one exists;
631
+ (3) last resort, grow the canvas downward. Steps 2-3 replace the old
632
+ "place at random, may overlap" fallback that caused the mosaic_004 overlaps.
633
+ Returns the (possibly grown) canvas size so the caller normalises YOLO
634
+ coordinates against the right dimensions.
635
+ """
636
+ cw, ch = canvas_size
637
+ placements_by_id = {}
638
+ occupied = [] # list of (x, y, alpha_mask)
639
+
640
+ # Place larger fragments first to ease packing
641
+ order = sorted(range(len(fragments_data)),
642
+ key=lambda k: -fragments_data[k]['rgba_rotated'].shape[0] *
643
+ fragments_data[k]['rgba_rotated'].shape[1])
644
+
645
+ for k in order:
646
+ rgba = fragments_data[k]['rgba_rotated']
647
+ h, w = rgba.shape[:2]
648
+ alpha = rgba[..., 3] > 0
649
+
650
+ # Fragment larger than the canvas → grow so it (and the random range) fit.
651
+ while w + 2 * padding > cw:
652
+ cw += w
653
+ while h + 2 * padding > ch:
654
+ ch += h
655
+
656
+ pos = None
657
+ for _ in range(max_tries):
658
+ x = random.randint(padding, cw - w - padding)
659
+ y = random.randint(padding, ch - h - padding)
660
+ if not _collides(x, y, alpha, occupied):
661
+ pos = (x, y)
662
+ break
663
+
664
+ if pos is None:
665
+ # Random search exhausted: deterministic scan is guaranteed to find a
666
+ # gap if the canvas still has room (mosaic_004 fix).
667
+ step = max(16, min(h, w) // 2)
668
+ pos = _scan_free_position(alpha, occupied, cw, ch, padding, step)
669
+
670
+ if pos is None:
671
+ # Canvas genuinely full: add a strip at the bottom and drop it there.
672
+ pos = (padding, ch + padding)
673
+ ch += h + 2 * padding
674
+
675
+ x, y = pos
676
+ placements_by_id[k] = {'x': x, 'y': y, 'w': w, 'h': h}
677
+ occupied.append((x, y, alpha))
678
+
679
+ canvas = Image.new('RGB', (cw, ch), (255, 255, 255))
680
+ placements = []
681
+ # Paste in original index order (deterministic z-order).
682
+ for idx, fdata in enumerate(fragments_data):
683
+ place = placements_by_id[idx]
684
+ pil = Image.fromarray(fdata['rgba_rotated'], 'RGBA')
685
+ canvas.paste(pil, (place['x'], place['y']), pil)
686
+ placements.append(place)
687
+ return canvas, placements, (cw, ch)
688
+
689
+
690
+ # ============================================================
691
+ # 9. YOLO polygon export from rotated alpha
692
+ # ============================================================
693
+
694
+ def extract_yolo_polygon(rgba_rotated, place_x, place_y, canvas_size, simplify_epsilon=1.5):
695
+ alpha = (rgba_rotated[..., 3] > 0).astype(np.uint8)
696
+ contours, _ = cv2.findContours(alpha, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
697
+ if not contours:
698
+ return None
699
+ cnt = max(contours, key=cv2.contourArea)
700
+ if simplify_epsilon > 0:
701
+ cnt = cv2.approxPolyDP(cnt, simplify_epsilon, True)
702
+ cnt = cnt.reshape(-1, 2).astype(np.float32)
703
+ cnt[:, 0] = (cnt[:, 0] + place_x) / canvas_size[0]
704
+ cnt[:, 1] = (cnt[:, 1] + place_y) / canvas_size[1]
705
+ return cnt
706
+
707
+
708
+ # ============================================================
709
+ # 10. Top-level orchestration
710
+ # ============================================================
711
+
712
+ def forge_one(target_path, out_dir, n_sides_range, n_frag_range, canvas_size,
713
+ stud_size, seed, degrade=None, rotate=True, placement='scatter',
714
+ frag_distribution='balanced', debug=False,
715
+ max_area_loss=MAX_AREA_LOSS_DEFAULT):
716
+ if seed is not None:
717
+ random.seed(seed)
718
+ np.random.seed(seed)
719
+
720
+ degrade = degrade or {}
721
+ erode_rng = tuple(degrade.get('erode_px', (0, 0)))
722
+ holes_rng = tuple(degrade.get('holes', (0, 0)))
723
+ missing_rng = tuple(degrade.get('missing', (0, 0))) # absolute count [min, max]
724
+
725
+ out_dir = Path(out_dir)
726
+ out_dir.mkdir(parents=True, exist_ok=True)
727
+ (out_dir / 'fragments').mkdir(exist_ok=True) # toujours écrit (entrée du VLM)
728
+
729
+ pil = Image.open(target_path).convert('RGB')
730
+ img = np.array(pil)
731
+ H, W = img.shape[:2]
732
+ if stud_size is None:
733
+ # Grille la PLUS FINE valide : plus grand g divisant l'image avec un
734
+ # stud résultant ≥ 40 px (contrainte projet : ≥40 px/stud). Désambiguïse
735
+ # les images divisibles par plusieurs tailles (ex. 3840 = 48·80 = 96·40
736
+ # → grille 96, stud 40) au lieu de retomber sur la grille la plus
737
+ # grossière. Les mosaïques 1920 restent en grille 48 (stud 40).
738
+ candidates = [g for g in (48, 50, 64, 96, 100, 128)
739
+ if W % g == 0 and H % g == 0 and W // g >= 40]
740
+ stud_size = W // max(candidates) if candidates else 40
741
+ print(f"[forge] image {W}x{H}, stud_size={stud_size} → grid {W // stud_size}x{H // stud_size}")
742
+
743
+ print("[forge] detecting LEGO pieces…")
744
+ pieces = detect_pieces(img, stud_size)
745
+ print(f"[forge] {len(pieces)} pieces detected")
746
+
747
+ n_cols, n_rows = W // stud_size, H // stud_size
748
+ warnings = sanity_check_pieces(pieces, n_cols, n_rows)
749
+ for w in warnings:
750
+ print(f"[warn] {w}")
751
+
752
+ piece_graph = build_piece_graph(pieces)
753
+
754
+ k = random.randint(n_frag_range[0], n_frag_range[1])
755
+ print(f"[forge] fragmenting into {k} fragments ({frag_distribution})…")
756
+ # ultracompact = compact appliqué à des mosaïques 1×1 (mode mono) → la
757
+ # fragmentation est la MÊME que compact ; "l'ultra" vient de l'input 1×1.
758
+ if frag_distribution in ('compact', 'ultracompact'):
759
+ piece_to_frag = fragment_pieces_compact(piece_graph, pieces, k)
760
+ else:
761
+ piece_to_frag = fragment_pieces(piece_graph, k)
762
+ frag_pieces = collections.defaultdict(list)
763
+ for pid, fid in piece_to_frag.items():
764
+ frag_pieces[fid].append(pid)
765
+ actual_k = len(frag_pieces)
766
+ print(f"[forge] {actual_k} non-empty fragments")
767
+
768
+ adjacencies, cell_to_frag = compute_fragment_adjacencies(pieces, piece_to_frag, stud_size)
769
+ print(f"[forge] {len(adjacencies)} fragment-fragment adjacencies")
770
+
771
+ print("[forge] extracting polygons & features per fragment…")
772
+ fragment_data = []
773
+ sorted_fids = sorted(frag_pieces.keys())
774
+ fid_to_idx = {fid: idx for idx, fid in enumerate(sorted_fids)}
775
+
776
+ for fid in sorted_fids:
777
+ all_cells = []
778
+ weighted_color = np.zeros(3, dtype=np.float64)
779
+ total_cells = 0
780
+ for pid in frag_pieces[fid]:
781
+ all_cells.extend(pieces[pid]['cells'])
782
+ n_cells = len(pieces[pid]['cells'])
783
+ weighted_color += np.array(pieces[pid]['color'], dtype=np.float64) * n_cells
784
+ total_cells += n_cells
785
+ mean_color = (weighted_color / max(total_cells, 1)).tolist()
786
+
787
+ mask = fragment_mask(all_cells, img.shape, stud_size)
788
+ polygon_raw = extract_polygon(mask) # PERFECT footprint → GT
789
+ # --- degradation: input only (the GT polygon_raw stays perfect) ---
790
+ erode_px = random.randint(*erode_rng) if erode_rng[1] > 0 else 0
791
+ n_holes = random.randint(*holes_rng) if holes_rng[1] > 0 else 0
792
+ if erode_px or n_holes:
793
+ mask_in = degrade_mask(mask, erode_px, n_holes, stud_size)
794
+ polygon_raw_deg = extract_polygon(mask_in)
795
+ if len(polygon_raw_deg) >= 4:
796
+ # erosion/holes add rasterisation noise (1px stair-steps) that
797
+ # would explode #reflex → simplify so reco B keeps n reasonable.
798
+ eps = max(1.5, stud_size * 0.06)
799
+ cnt = polygon_raw_deg.reshape(-1, 1, 2).astype(np.float32)
800
+ polygon_raw_deg = cv2.approxPolyDP(cnt, eps, True).reshape(-1, 2).astype(np.float32)
801
+ if len(polygon_raw_deg) < 4: # degradation wiped it → revert
802
+ mask_in = (mask > 0).astype(np.uint8)
803
+ polygon_raw_deg = polygon_raw
804
+ else:
805
+ mask_in = (mask > 0).astype(np.uint8)
806
+ polygon_raw_deg = polygon_raw
807
+
808
+ # Degradation severity = area lost by the degraded footprint vs the
809
+ # perfect one (DERIVED metric, not an input knob — cf. reco/06/06).
810
+ perf_area = abs(_polygon_signed_area(polygon_raw)) if len(polygon_raw) >= 3 else 0.0
811
+ deg_area = abs(_polygon_signed_area(np.asarray(polygon_raw_deg, dtype=np.float64))) \
812
+ if len(polygon_raw_deg) >= 3 else 0.0
813
+ lost_frac = float(1.0 - deg_area / perf_area) if perf_area > 0 else 0.0
814
+
815
+ # reco B : budget sur la PERTE D'AIRE (ε), n en sortie. `n_sides_range`
816
+ # est CONSERVÉ comme plancher optionnel mais n'est plus le budget — cf.
817
+ # resample_reflex_aware (correctif 23/07/2026).
818
+ polygon_n = resample_reflex_aware(polygon_raw_deg, n_min=0,
819
+ max_area_loss=max_area_loss) # INPUT, ⊆ perfect
820
+ centroid = polygon_n.mean(axis=0)
821
+ # rotation-invariance : repère canonique PCA (sur le masque observé)
822
+ R = pca_canonical_rotation(mask_in)
823
+ polygon_canon = ((polygon_n - centroid) @ R.T).astype(np.float32)
824
+ pca_angle = float(np.degrees(np.arctan2(R[0, 1], R[0, 0]))) # axe majeur (repère image)
825
+
826
+ global_feat, side_feat = compute_fragment_features(
827
+ polygon_n, float(len(all_cells) * stud_size * stud_size),
828
+ mean_color, img, polygon_geom=polygon_canon
829
+ )
830
+ outer_per_side = find_outer_fragments_per_side(
831
+ polygon_n, centroid, fid, cell_to_frag, stud_size
832
+ )
833
+ # Translate fragment_id → contiguous node index
834
+ outer_per_side = [fid_to_idx[o] if o is not None and o in fid_to_idx else None
835
+ for o in outer_per_side]
836
+
837
+ rgba, bbox = make_fragment_rgba(all_cells, img, stud_size, mask=mask_in)
838
+ # rotate=False → curriculum L1 : fragments éclatés par TRANSLATION seule
839
+ # (palier le plus facile : YOLO/pose n'a pas à résoudre l'orientation).
840
+ angle = (random.choice([0, 90, 180, 270]) + random.uniform(-5.0, 5.0)) if rotate else 0.0
841
+ rgba_rot = rotate_rgba(rgba, angle) if rotate else rgba
842
+
843
+ fragment_data.append({
844
+ 'node_id': fid_to_idx[fid],
845
+ 'cells': all_cells,
846
+ 'piece_ids': frag_pieces[fid],
847
+ 'polygon_raw': polygon_raw.tolist(),
848
+ 'polygon_raw_degraded': np.asarray(polygon_raw_deg).tolist(),
849
+ 'degradation_lost_frac': lost_frac,
850
+ 'erode_px': int(erode_px),
851
+ 'n_holes': int(n_holes),
852
+ 'polygon_n': polygon_n.tolist(),
853
+ 'polygon_n_canonical': polygon_canon.tolist(), # repère PCA (invariant rotation)
854
+ 'pca_angle_deg': pca_angle,
855
+ 'global_features': global_feat,
856
+ 'side_features': side_feat,
857
+ 'mean_color': [float(c) for c in mean_color],
858
+ 'rgba': rgba,
859
+ 'rgba_rotated': rgba_rot,
860
+ 'rotation_angle': float(angle),
861
+ 'bbox_in_target': bbox,
862
+ 'outer_per_side': outer_per_side,
863
+ })
864
+
865
+ # --- missing fragments: removed from the exploded INPUT, kept in the GT ---
866
+ missing_ids = set()
867
+ if missing_rng[1] > 0 and len(fragment_data) > 1:
868
+ n_missing = min(random.randint(missing_rng[0], missing_rng[1]),
869
+ len(fragment_data) - 1) # keep at least one fragment
870
+ if n_missing > 0:
871
+ missing_ids = set(random.sample(
872
+ [f['node_id'] for f in fragment_data], n_missing))
873
+ print(f"[forge] {len(missing_ids)} fragment(s) marked missing (input only)")
874
+ present = [f for f in fragment_data if f['node_id'] not in missing_ids]
875
+
876
+ if placement == 'explode':
877
+ # L0 : vue éclatée (positions relatives conservées, juste espacées)
878
+ print("[forge] placing fragments (exploded view, relative layout kept)…")
879
+ canvas, placements, canvas_size = explode_fragments(present, (W, H))
880
+ else:
881
+ print(f"[forge] placing fragments on {canvas_size[0]}x{canvas_size[1]} white canvas…")
882
+ requested_size = canvas_size
883
+ canvas, placements, canvas_size = place_fragments(present, canvas_size)
884
+ if canvas_size != requested_size:
885
+ print(f"[forge] canvas grown to {canvas_size[0]}x{canvas_size[1]} to fit all fragments")
886
+ for f, place in zip(present, placements):
887
+ f['placement'] = place
888
+
889
+ print("[forge] extracting YOLO polygons…")
890
+ yolo_lines = []
891
+ for fdata, place in zip(present, placements):
892
+ poly = extract_yolo_polygon(
893
+ fdata['rgba_rotated'], place['x'], place['y'], canvas_size
894
+ )
895
+ if poly is None:
896
+ continue
897
+ coords = ' '.join(f'{v:.6f}' for v in poly.flatten())
898
+ yolo_lines.append(f'0 {coords}')
899
+
900
+ print("[forge] writing outputs…")
901
+ pil.save(out_dir / 'target.png')
902
+ canvas.save(out_dir / 'source.png')
903
+ (out_dir / 'source_yolo.txt').write_text('\n'.join(yolo_lines) + '\n')
904
+
905
+ # Crops par fragment : toujours écrits (entrée du VLM).
906
+ for fdata in present:
907
+ Image.fromarray(fdata['rgba'], 'RGBA').save(
908
+ out_dir / 'fragments' / f"frag_{fdata['node_id']:02d}.png"
909
+ )
910
+ # pieces.json = DEBUG pur (pièces LEGO détectées) : n'entraîne PAS le YOLO (c'est
911
+ # source_yolo.txt), pas lu par visualize.py, lu NULLE PART → OFF par défaut,
912
+ # opt-in via --debug (~−0.8 Mo/instance, soit ~20 Go sur 25 000).
913
+ if debug:
914
+ pieces_json = [{
915
+ 'cells': p['cells'],
916
+ 'bbox_grid': p['bbox_grid'],
917
+ 'color': p['color'],
918
+ } for p in pieces]
919
+ (out_dir / 'pieces.json').write_text(json.dumps(pieces_json, indent=2))
920
+
921
+ # Build two node representations:
922
+ # - 'gnn_input': features the GNN may legitimately consume (no target-frame
923
+ # position leak). polygon_n_canonical = polygon centred at the origin.
924
+ # - 'target_info': ground-truth position/orientation, used as supervision
925
+ # and for viz. NOT to be fed to the GNN as input.
926
+ def split_node(f):
927
+ gf = f['global_features'] # [area, perim, cx, cy, R, G, B, bbox_w, bbox_h]
928
+ # gnn_input = DOMAINE-AGNOSTIQUE (transférable LEGO→fresque) — aucune feature LEGO-only.
929
+ gnn_input = [gf[0], gf[1], gf[4], gf[5], gf[6], gf[7], gf[8]] # area, perim, R, G, B, bbox_w, bbox_h
930
+ return {
931
+ 'gnn_input': gnn_input,
932
+ 'n_sides': len(f['polygon_n_canonical']),
933
+ 'polygon_n_canonical': f['polygon_n_canonical'], # repère PCA (invariant rotation)
934
+ 'side_features': f['side_features'],
935
+ 'target_info': {
936
+ 'centroid': [gf[2], gf[3]],
937
+ 'pca_angle_deg': f['pca_angle_deg'], # orientation retirée de l'input → GT
938
+ 'polygon_n_absolute': f['polygon_n'],
939
+ 'polygon_raw': f['polygon_raw'],
940
+ 'mean_color': f['mean_color'],
941
+ 'n_pieces': len(f['piece_ids']),
942
+ },
943
+ }
944
+
945
+ mean_lost = (float(np.mean([f['degradation_lost_frac'] for f in fragment_data]))
946
+ if fragment_data else 0.0)
947
+ nodes_full = [{'node_id': f['node_id'], 'missing': f['node_id'] in missing_ids,
948
+ **split_node(f)} for f in fragment_data]
949
+ # graph_fragments = INPUT: missing fragments are not observed → excluded.
950
+ nodes_input_only = [
951
+ {k: v for k, v in n.items() if k not in ('target_info', 'missing')}
952
+ for n in nodes_full if not n['missing']
953
+ ]
954
+
955
+ edges_json = []
956
+ for (fa, fb), segments in adjacencies.items():
957
+ a = fid_to_idx[fa]
958
+ b = fid_to_idx[fb]
959
+ total_length = float(sum(
960
+ np.sqrt((s[2] - s[0]) ** 2 + (s[3] - s[1]) ** 2) for s in segments
961
+ ))
962
+ angles = [float(np.arctan2(s[3] - s[1], s[2] - s[0])) for s in segments]
963
+ mean_angle = float(np.mean(angles))
964
+ a_sides = [i for i, o in enumerate(fragment_data[a]['outer_per_side']) if o == b]
965
+ b_sides = [i for i, o in enumerate(fragment_data[b]['outer_per_side']) if o == a]
966
+ edges_json.append({
967
+ 'src': a, 'dst': b,
968
+ 'features': [total_length, mean_angle, float(len(segments))],
969
+ 'src_side_idx': a_sides,
970
+ 'dst_side_idx': b_sides,
971
+ 'polyline_raw': [list(s) for s in segments],
972
+ })
973
+
974
+ common_meta = {
975
+ 'max_area_loss': max_area_loss, # ε — LE budget de reco B (fidélité)
976
+ 'n_sides_range': list(n_sides_range), # OBSOLÈTE depuis le 23/07/2026 (info seule)
977
+ 'n_sides_note': ("polygon_n_canonical / side_features ont une longueur "
978
+ "VARIABLE par nœud (cf. champ 'n_sides' de chaque nœud). "
979
+ "Reco B reflex-aware : polygon_n ⊆ polygon_raw (l'aire "
980
+ "n'est jamais gagnée). Plancher dur = nb de sommets "
981
+ "concaves. Pour un tenseur fixe côté GNN : padder au max "
982
+ "des 'n_sides' du dataset + masque de validité."),
983
+ 'gnn_input_feature_names': ['area', 'perimeter', 'R', 'G', 'B', 'bbox_w', 'bbox_h'],
984
+ 'feature_convention_note': (
985
+ "gnn_input = features 100 % DOMAINE-AGNOSTIQUES (transférables LEGO→fresque ; "
986
+ "aucune feature LEGO-only). polygon_n_canonical / side_features ont une longueur "
987
+ "VARIABLE (n_sides) → côté GNN : padder à n_max + masque (cf. features/collate.py), "
988
+ "ou set-encoder. area/perimeter/bbox sont en PIXELS (non normalisés) ; "
989
+ "normaliser avant transfert cross-échelle."),
990
+ 'side_feature_names': ['length', 'angle', 'R', 'G', 'B'],
991
+ 'edge_feature_names': ['shared_length', 'mean_angle', 'n_segments'],
992
+ 'target_info_note': "centroid/polygon_n_absolute/polygon_raw are in the "
993
+ "target frame and MUST NOT be fed to the GNN as "
994
+ "input — they are supervision targets / metadata.",
995
+ 'degradation': {
996
+ 'erode_px': list(erode_rng),
997
+ 'holes': list(holes_rng),
998
+ 'missing': list(missing_rng),
999
+ 'n_missing': len(missing_ids),
1000
+ 'mean_lost_frac': round(mean_lost, 4), # sévérité moyenne (métrique dérivée)
1001
+ 'note': "Dégradation appliquée à l'INPUT seulement ; la GT (arêtes + "
1002
+ "target_info.polygon_raw perfect) reste sur la partition intacte. "
1003
+ "mean_lost_frac = aire moyenne perdue (parfait→dégradé), métrique "
1004
+ "post-hoc de sévérité, pas un paramètre d'entrée.",
1005
+ },
1006
+ }
1007
+
1008
+ graph_complete = dict(common_meta, nodes=nodes_full, edges=edges_json)
1009
+ (out_dir / 'graph_complete.json').write_text(json.dumps(graph_complete, indent=2))
1010
+
1011
+ graph_fragments = dict(common_meta, nodes=nodes_input_only, edges=[])
1012
+ (out_dir / 'graph_fragments.json').write_text(json.dumps(graph_fragments, indent=2))
1013
+
1014
+ # gt_layout.json — ground truth for the RECONSTRUCTION metric (IoU / Q_pos).
1015
+ # Per fragment: its exact footprint in target.png (polygon_raw) + the reco-B
1016
+ # polygon, both in target coords, plus where it sits in the exploded source.
1017
+ # The GNN+pose / VLM prediction is scored against these placed polygons.
1018
+ gt_fragments = []
1019
+ for f in fragment_data:
1020
+ gf = f['global_features']
1021
+ place = f.get('placement')
1022
+ gt_fragments.append({
1023
+ 'node_id': f['node_id'],
1024
+ 'missing': f['node_id'] in missing_ids,
1025
+ 'polygon_raw': f['polygon_raw'], # PERFECT footprint, target coords
1026
+ 'polygon_raw_degraded': f['polygon_raw_degraded'], # what the model sees (eroded/holed)
1027
+ 'degradation_lost_frac': round(f['degradation_lost_frac'], 4),
1028
+ 'polygon_n': f['polygon_n'], # reco-B polygon, target coords
1029
+ 'centroid': [gf[2], gf[3]],
1030
+ 'bbox_target': list(f['bbox_in_target']),
1031
+ 'area': gf[0],
1032
+ 'source_placement': ( # location in source.png (exploded)
1033
+ {'x': place['x'], 'y': place['y'], 'w': place['w'], 'h': place['h'],
1034
+ 'rotation_deg': f['rotation_angle']}
1035
+ if place is not None else None # None ⟺ missing fragment
1036
+ ),
1037
+ })
1038
+ gt_layout = {
1039
+ 'mosaic': out_dir.name,
1040
+ 'target_size': [W, H],
1041
+ 'canvas_size': [canvas_size[0], canvas_size[1]],
1042
+ 'mean_degradation_lost_frac': round(mean_lost, 4),
1043
+ 'note': ("Vérité terrain pour la métrique de RECONSTRUCTION (IoU / Q_pos). "
1044
+ "polygon_raw = footprint exact du fragment dans target.png ; on y "
1045
+ "compare la prédiction GNN+pose / VLM (fragment replacé). "
1046
+ "source_placement = pose du fragment dans source.png (éclaté)."),
1047
+ 'fragments': gt_fragments,
1048
+ }
1049
+ (out_dir / 'gt_layout.json').write_text(json.dumps(gt_layout, indent=2))
1050
+
1051
+ # degradation.md — rapport lisible : paramètres tirés + aire perdue par fragment
1052
+ report = [
1053
+ f"# Dégradation — {out_dir.name}", "",
1054
+ "## Configuration (intervalles ; tirage aléatoire par fragment)",
1055
+ f"- Érosion morpho : `{list(erode_rng)}` px",
1056
+ f"- Trous internes : `{list(holes_rng)}` (aire totale plafonnée à 10 % du fragment)",
1057
+ f"- Fragments manquants : `{list(missing_rng)}` → **{len(missing_ids)}** tiré(s)",
1058
+ f"- Reco B — perte d'aire tolérée : `{max_area_loss:.1%}` (ε ; n en sortie, "
1059
+ f"plancher dur = #reflex)", "",
1060
+ "## Par fragment",
1061
+ "| node_id | manquant | érosion px | trous | n sommets | aire perdue % |",
1062
+ "|---:|:---:|---:|---:|---:|---:|",
1063
+ ]
1064
+ for f in fragment_data:
1065
+ report.append(
1066
+ f"| {f['node_id']} | {'oui' if f['node_id'] in missing_ids else '—'} "
1067
+ f"| {f['erode_px']} | {f['n_holes']} | {len(f['polygon_n'])} "
1068
+ f"| {100 * f['degradation_lost_frac']:.1f} |")
1069
+ report += [
1070
+ "", "## Résumé",
1071
+ f"- **Aire moyenne perdue par fragment : {100 * mean_lost:.2f} %**",
1072
+ f"- Fragments manquants : {sorted(missing_ids) if missing_ids else 'aucun'}",
1073
+ f"- Total fragments : {len(fragment_data)} (présents dans l'input : {len(present)})",
1074
+ "",
1075
+ ]
1076
+ (out_dir / 'degradation.md').write_text("\n".join(report))
1077
+
1078
+ print(f"[forge] done → {out_dir}")
1079
+ print(f" pieces={len(pieces)} fragments={len(fragment_data)} "
1080
+ f"adjacencies={len(edges_json)}")
1081
+
1082
+
1083
+ def parse_args():
1084
+ p = argparse.ArgumentParser(description=__doc__)
1085
+ p.add_argument('--input', default='exp1/canvas_mosaic.png',
1086
+ help='Path to canvas_mosaic.png (target)')
1087
+ p.add_argument('--out', default='dataset/mosaic_001',
1088
+ help='Output directory')
1089
+ p.add_argument('--seed', type=int, default=42)
1090
+ p.add_argument('--n-sides-min', type=int, default=16,
1091
+ help='Min target vertex count per fragment (reco B, variable n)')
1092
+ p.add_argument('--n-sides-max', type=int, default=24,
1093
+ help='Max target vertex count per fragment (floor = #reflex)')
1094
+ p.add_argument('--max-area-loss', type=float, default=MAX_AREA_LOSS_DEFAULT,
1095
+ help="reco B — fraction d'aire que polygon_n a le droit de PERDRE "
1096
+ "vs polygon_raw (défaut 0.01 = 1%%). C'est LE budget ; le nombre "
1097
+ "de sommets en découle. Remplace --n-sides-min/max (23/07/2026)")
1098
+ p.add_argument('--n-frag-min', type=int, default=10)
1099
+ p.add_argument('--n-frag-max', type=int, default=15)
1100
+ p.add_argument('--canvas-w', type=int, default=3500)
1101
+ p.add_argument('--canvas-h', type=int, default=3500)
1102
+ p.add_argument('--stud-size', type=int, default=None,
1103
+ help='Pixels per stud (auto-detected from image size if omitted)')
1104
+ p.add_argument('--no-rotation', action='store_true',
1105
+ help='Curriculum L1 : fragments éclatés SANS rotation (translation seule)')
1106
+ p.add_argument('--placement', choices=['scatter', 'explode'], default='scatter',
1107
+ help="explode = curriculum L0 : vue éclatée (positions relatives "
1108
+ "gardées, juste espacées) ; scatter = placement aléatoire (défaut)")
1109
+ p.add_argument('--frag-distribution', choices=['balanced', 'compact', 'ultracompact'],
1110
+ default='balanced',
1111
+ help="motif de découpe : balanced (BFS, défaut), compact (~rectangulaire), "
1112
+ "ou ultracompact (= compact, à utiliser sur des mosaïques 1×1 `--mode mono`). "
1113
+ "voronoi/clusters = à venir")
1114
+ p.add_argument('--debug', action='store_true',
1115
+ help="écrit aussi pieces.json (debug du détecteur de pièces, lu nulle "
1116
+ "part) ; OFF par défaut")
1117
+ # --- degradation knobs (curriculum) ; all default OFF → clean reco-B ---
1118
+ p.add_argument('--erode-px-min', type=int, default=0,
1119
+ help='Min boundary-erosion radius in px (DAFNE E)')
1120
+ p.add_argument('--erode-px-max', type=int, default=0,
1121
+ help='Max boundary-erosion radius in px (0 = no erosion)')
1122
+ p.add_argument('--holes-min', type=int, default=0,
1123
+ help='Min interior holes per fragment')
1124
+ p.add_argument('--holes-max', type=int, default=0,
1125
+ help='Max interior holes per fragment (0 = no holes)')
1126
+ p.add_argument('--missing-min', type=int, default=0,
1127
+ help='Min number of fragments removed from the input (DAFNE C)')
1128
+ p.add_argument('--missing-max', type=int, default=0,
1129
+ help='Max number of fragments removed from the input (0 = none)')
1130
+ return p.parse_args()
1131
+
1132
+
1133
+ def degrade_from_args(args):
1134
+ return {
1135
+ 'erode_px': (args.erode_px_min, args.erode_px_max),
1136
+ 'holes': (args.holes_min, args.holes_max),
1137
+ 'missing': (args.missing_min, args.missing_max),
1138
+ }
1139
+
1140
+
1141
+ def main():
1142
+ args = parse_args()
1143
+ forge_one(
1144
+ target_path=args.input,
1145
+ out_dir=args.out,
1146
+ n_sides_range=(args.n_sides_min, args.n_sides_max),
1147
+ max_area_loss=args.max_area_loss,
1148
+ n_frag_range=(args.n_frag_min, args.n_frag_max),
1149
+ canvas_size=(args.canvas_w, args.canvas_h),
1150
+ stud_size=args.stud_size,
1151
+ seed=args.seed,
1152
+ degrade=degrade_from_args(args),
1153
+ rotate=not args.no_rotation,
1154
+ placement=args.placement,
1155
+ frag_distribution=args.frag_distribution,
1156
+ debug=args.debug,
1157
+ )
1158
+
1159
+
1160
+ if __name__ == '__main__':
1161
+ main()
code/mosaic2fragments/visualize.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Quick visualization: overlay YOLO polygons on source.png to check alignment.
3
+
4
+ Also reports any sanity-check failures (fragment count vs YOLO lines, etc.).
5
+ """
6
+
7
+ import argparse
8
+ import json
9
+ from pathlib import Path
10
+
11
+ import numpy as np
12
+ from PIL import Image, ImageDraw
13
+
14
+
15
+ COLORS = [
16
+ (231, 76, 60), (52, 152, 219), (241, 196, 15), (46, 204, 113),
17
+ (155, 89, 182), (52, 73, 94), (230, 126, 34), (26, 188, 156),
18
+ (192, 57, 43), (41, 128, 185), (243, 156, 18), (39, 174, 96),
19
+ (142, 68, 173), (44, 62, 80), (211, 84, 0), (22, 160, 133),
20
+ ]
21
+
22
+
23
+ def visualize(dataset_dir):
24
+ d = Path(dataset_dir)
25
+ src = Image.open(d / 'source.png').convert('RGBA')
26
+ W, H = src.size
27
+
28
+ overlay = Image.new('RGBA', src.size, (0, 0, 0, 0))
29
+ draw = ImageDraw.Draw(overlay)
30
+
31
+ with open(d / 'source_yolo.txt') as f:
32
+ lines = [l.strip() for l in f if l.strip()]
33
+ print(f"YOLO lines: {len(lines)}")
34
+
35
+ for idx, line in enumerate(lines):
36
+ parts = line.split()
37
+ cls = parts[0]
38
+ coords = [float(x) for x in parts[1:]]
39
+ pts = [(coords[i] * W, coords[i + 1] * H) for i in range(0, len(coords), 2)]
40
+ color = COLORS[idx % len(COLORS)]
41
+ draw.polygon(pts, outline=color + (255,), fill=color + (90,))
42
+
43
+ out = Image.alpha_composite(src, overlay)
44
+ out_path = d / 'source_yolo_viz.png'
45
+ out.convert('RGB').save(out_path)
46
+ print(f"Wrote {out_path}")
47
+
48
+ # Sanity: cross-check with graph_complete.json
49
+ g = json.loads((d / 'graph_complete.json').read_text())
50
+ print(f"Graph nodes: {len(g['nodes'])}")
51
+ print(f"Graph edges: {len(g['edges'])}")
52
+ sizes = [n['target_info']['n_pieces'] for n in g['nodes']] # n_pieces (métadonnée GT)
53
+ print(f"Fragment sizes (n_pieces): min={min(sizes):.0f} max={max(sizes):.0f} "
54
+ f"mean={np.mean(sizes):.1f}")
55
+
56
+
57
+ def visualize_recob(dataset_dir):
58
+ """Viz des DEUX pertes d'aire, en repère target (depuis `gt_layout.json`).
59
+
60
+ Par fragment, trois couches :
61
+ couleur pâle = `polygon_raw` (empreinte PARFAITE)
62
+ hachures GRISES fines = perte de DÉGRADATION (raw − raw_degraded :
63
+ érosion, trous — voulue, c'est l'input L3/L4)
64
+ hachures COULEUR marquées = perte d'ENCODAGE reco-B (raw_degraded −
65
+ polygon_n : budget --max-area-loss, ~ε)
66
+ trait noir = `polygon_n` (ce que voit le GNN)
67
+ NB : `source.png` n'est PAS affecté par la perte d'encodage (vrais pixels
68
+ découpés par le masque dégradé) — elle n'existe que dans polygon_n.
69
+ """
70
+ import cv2
71
+
72
+ d = Path(dataset_dir)
73
+ gl = json.loads((d / 'gt_layout.json').read_text())
74
+ W, H = gl['target_size']
75
+ img = np.full((H, W, 3), 255, dtype=np.uint8)
76
+
77
+ hatch = np.zeros((H, W), dtype=np.uint8) # trame diagonale //
78
+ for c in range(-H, W, 14):
79
+ cv2.line(hatch, (c, 0), (c + H, H), 1, 2)
80
+ hatch2 = np.zeros((H, W), dtype=np.uint8) # trame croisée \\ serrée
81
+ for c in range(-H, W, 8):
82
+ cv2.line(hatch2, (c + H, 0), (c, H), 1, 1)
83
+
84
+ deg_total = enc_total = raw_total = 0.0
85
+ for idx, f in enumerate(gl['fragments']):
86
+ raw = np.array(f['polygon_raw'], dtype=np.int32)
87
+ deg = np.array(f['polygon_raw_degraded'], dtype=np.int32)
88
+ enc = np.array(f['polygon_n'], dtype=np.int32)
89
+ color = COLORS[idx % len(COLORS)]
90
+ pale = tuple(int(v + (255 - v) * 0.72) for v in color)
91
+ m = {}
92
+ for k, poly in (('raw', raw), ('deg', deg), ('enc', enc)):
93
+ m[k] = np.zeros((H, W), dtype=np.uint8)
94
+ if len(poly) >= 3:
95
+ cv2.fillPoly(m[k], [poly], 1)
96
+ lost_deg = (m['raw'] > 0) & (m['deg'] == 0) # dégradation (voulue)
97
+ lost_enc = (m['deg'] > 0) & (m['enc'] == 0) # encodage reco-B (ε)
98
+ img[m['raw'] > 0] = pale
99
+ img[lost_deg & (hatch2 > 0)] = (150, 150, 150)
100
+ img[lost_enc & (hatch > 0)] = color
101
+ if len(enc) >= 3:
102
+ cv2.polylines(img, [enc], True, (0, 0, 0), 2)
103
+ deg_total += float(lost_deg.sum())
104
+ enc_total += float(lost_enc.sum())
105
+ raw_total += float((m['raw'] > 0).sum())
106
+
107
+ out_path = d / 'recob_viz.png'
108
+ Image.fromarray(img).save(out_path)
109
+ print(f"Wrote {out_path} (perte dégradation [hachures grises] : "
110
+ f"{100 * deg_total / max(raw_total, 1):.2f} % ; perte encodage reco-B "
111
+ f"[hachures couleur] : {100 * enc_total / max(raw_total, 1):.2f} %)")
112
+
113
+
114
+ def parse_args():
115
+ p = argparse.ArgumentParser()
116
+ p.add_argument('--dir', default='dataset/mosaic_001')
117
+ p.add_argument('--recob', action='store_true',
118
+ help="écrit aussi recob_viz.png (perte d'encodage reco-B hachurée)")
119
+ return p.parse_args()
120
+
121
+
122
+ if __name__ == '__main__':
123
+ a = parse_args()
124
+ visualize(a.dir)
125
+ if a.recob:
126
+ visualize_recob(a.dir)
code/requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Dependencies (Python 3.11+). Install:
2
+ # python3 -m venv .venv && source .venv/bin/activate && pip install -r requirements.txt
3
+ numpy==2.2.6
4
+ Pillow==12.0.0
5
+ opencv-python==4.13.0.92
6
+ shapely==2.1.2 # optionnel (clip de sécurité reco-B) ; sans lui, fallback gracieux
7
+ networkx==3.5
8
+ datasets==4.3.0 # source d'images wikiart en streaming (forge_LAR_2mosaic/wikiart.py)
9
+ huggingface_hub==1.4.1 # upload de dataset vers le Hub (tools/hf_upload.py)
code/tools/hf_export_tars.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Exporte un dataset curriculum (`<src>/L*/`) vers le HF Hub en **tar.gz par palier**.
3
+
4
+ Un dataset de 25 000 instances = ~500 k fichiers → un upload browsable est
5
+ impraticable (HF rame/refuse au-delà de ~100 k fichiers). On archive donc CHAQUE
6
+ palier (`L0_explode/`, …) en un seul `.tar.gz`, on l'uploade, puis on **supprime
7
+ l'archive locale** avant de passer au suivant → pic disque ≈ une seule archive.
8
+
9
+ En bonus on pousse les `gnn_meta.json` (browsables, petits) et, optionnellement,
10
+ on supprime d'anciens dossiers *legacy* du repo.
11
+
12
+ Prérequis : `huggingface-cli login` (ou HF_TOKEN). `HF_HUB_ENABLE_HF_TRANSFER=1`
13
+ recommandé pour la vitesse.
14
+
15
+ Exemple :
16
+ HF_HUB_ENABLE_HF_TRANSFER=1 python3 forge_mosaics/tools/hf_export_tars.py \
17
+ --src output/poly_balanced/k10-15 --repo-id <user>/<dataset-repo> \
18
+ --path-in-repo poly_balanced/k10-15 --card /tmp/hf_card.md
19
+ """
20
+ import argparse
21
+ import os
22
+ import subprocess
23
+ from pathlib import Path
24
+
25
+
26
+ def parse_args():
27
+ p = argparse.ArgumentParser(description=__doc__,
28
+ formatter_class=argparse.RawDescriptionHelpFormatter)
29
+ p.add_argument("--src", default="output/balanced", help="dossier contenant les paliers L*/")
30
+ p.add_argument("--repo-id", required=True)
31
+ p.add_argument("--path-in-repo", default="balanced", help="préfixe cible dans le repo")
32
+ p.add_argument("--tmp", default="output/_tars", help="dossier temporaire des archives")
33
+ p.add_argument("--delete-legacy", nargs="*", default=[],
34
+ help="dossiers du repo à supprimer après upload (ex: clean degraded)")
35
+ p.add_argument("--card", default=None, help="README.md (carte) à pousser à la racine")
36
+ p.add_argument("--overwrite", action="store_true",
37
+ help="ré-uploade même si le tar existe déjà sur le repo (écrase)")
38
+ p.add_argument("--token", default=None)
39
+ return p.parse_args()
40
+
41
+
42
+ def main():
43
+ a = parse_args()
44
+ from huggingface_hub import HfApi
45
+ api = HfApi(token=a.token)
46
+ api.create_repo(a.repo_id, repo_type="dataset", exist_ok=True)
47
+ src = Path(a.src)
48
+ tmp = Path(a.tmp); tmp.mkdir(parents=True, exist_ok=True)
49
+ paliers = sorted(d.name for d in src.iterdir() if d.is_dir() and d.name.startswith("L"))
50
+ print(f"paliers: {paliers}")
51
+
52
+ if a.card:
53
+ api.upload_file(path_or_fileobj=a.card, path_in_repo="README.md",
54
+ repo_id=a.repo_id, repo_type="dataset",
55
+ commit_message="carte : curriculum 5 paliers (remplace 100mosaics legacy)")
56
+ print("[card] poussée")
57
+
58
+ for L in paliers: # gnn_meta browsables (petits)
59
+ meta = src / L / "gnn_meta.json"
60
+ if meta.exists():
61
+ api.upload_file(path_or_fileobj=str(meta),
62
+ path_in_repo=f"{a.path_in_repo}/{L}.gnn_meta.json",
63
+ repo_id=a.repo_id, repo_type="dataset",
64
+ commit_message=f"meta {L}")
65
+ print(f"[meta] {L}")
66
+
67
+ for L in paliers: # 1 archive par palier
68
+ repo_path = f"{a.path_in_repo}/{L}.tar.gz"
69
+ if not a.overwrite and api.file_exists(a.repo_id, repo_path, repo_type="dataset"):
70
+ print(f"[skip] {L} (déjà sur le repo) — resume") # relance idempotente
71
+ continue
72
+ tar = tmp / f"{L}.tar.gz"
73
+ print(f"[tar] {L} …", flush=True)
74
+ # Les tars du 24-26/07/2026 contenaient un AppleDouble `._<fichier>`
75
+ # (163 o de xattrs macOS) à côté de CHAQUE fichier — bruit inutile dans
76
+ # un dataset public. Ceinture (COPYFILE_DISABLE) + bretelles
77
+ # (--no-mac-metadata, bsdtar) ; l'option est retirée si tar la rejette.
78
+ cmd = ["tar", "--no-mac-metadata", "-czf", str(tar), "-C", str(src), L]
79
+ env = {**os.environ, "COPYFILE_DISABLE": "1"}
80
+ if subprocess.run(cmd, env=env).returncode != 0:
81
+ subprocess.run(["tar", "-czf", str(tar), "-C", str(src), L],
82
+ check=True, env=env)
83
+ gb = tar.stat().st_size / 1e9
84
+ print(f"[upload] {L} ({gb:.1f} Go) …", flush=True)
85
+ api.upload_file(path_or_fileobj=str(tar), path_in_repo=repo_path,
86
+ repo_id=a.repo_id, repo_type="dataset",
87
+ commit_message=f"palier {L} (tar.gz)")
88
+ tar.unlink() # libère le disque avant le suivant
89
+ print(f"[done] {L}", flush=True)
90
+
91
+ for folder in a.delete_legacy:
92
+ try:
93
+ api.delete_folder(path_in_repo=folder, repo_id=a.repo_id, repo_type="dataset",
94
+ commit_message=f"retrait legacy {folder}")
95
+ print(f"[legacy] supprimé : {folder}")
96
+ except Exception as e:
97
+ print(f"[legacy] échec {folder}: {e}")
98
+
99
+ print(f"EXPORT FINI → https://huggingface.co/datasets/{a.repo_id}")
100
+
101
+
102
+ if __name__ == "__main__":
103
+ main()
code/tools/hf_upload.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Upload d'un dossier vers le HuggingFace Hub comme **dataset** — gratuit.
3
+
4
+ Le HF Hub héberge gratuitement les datasets (public ou privé, quotas larges).
5
+ C'est la façon recommandée de partager nos données avec les camarades : le CODE
6
+ reste sur GitHub (léger), les DONNÉES (mosaïques, datasets fragmentés) vont sur le
7
+ Hub — au lieu de gonfler le dépôt git.
8
+
9
+ Prérequis :
10
+ pip install huggingface_hub
11
+ huggingface-cli login # token gratuit : https://huggingface.co/settings/tokens
12
+ # (ou export HF_TOKEN=hf_xxx, ou --token hf_xxx)
13
+
14
+ Exemples :
15
+ # un dataset fragmenté, public
16
+ python3 forge_mosaics/tools/hf_upload.py --folder output/mosaics \
17
+ --repo-id <user>/<dataset-repo>
18
+
19
+ # un dataset privé
20
+ python3 forge_mosaics/tools/hf_upload.py --folder output/dataset \
21
+ --repo-id <user>/<dataset-repo> --private
22
+ """
23
+ import argparse
24
+
25
+
26
+ def parse_args():
27
+ p = argparse.ArgumentParser(description="Upload d'un dossier vers le HF Hub (dataset).")
28
+ p.add_argument("--folder", required=True, help="dossier local à uploader")
29
+ p.add_argument("--repo-id", required=True, help="ex: <user>/<dataset-repo>")
30
+ p.add_argument("--private", action="store_true", help="dataset privé (défaut : public)")
31
+ p.add_argument("--token", default=None, help="token HF (sinon : huggingface-cli login / HF_TOKEN)")
32
+ p.add_argument("--commit", default="upload via tools/hf_upload.py", help="message de commit Hub")
33
+ p.add_argument("--path-in-repo", default=None,
34
+ help="sous-dossier cible dans le repo (ex: clean) → plusieurs dossiers dans 1 dataset")
35
+ p.add_argument("--allow-patterns", nargs="*", default=None,
36
+ help="ne pousser que ces motifs (ex: '*.json' '*.png')")
37
+ return p.parse_args()
38
+
39
+
40
+ def main():
41
+ a = parse_args()
42
+ from huggingface_hub import HfApi # import tardif : message clair si absent
43
+ api = HfApi(token=a.token)
44
+ api.create_repo(repo_id=a.repo_id, repo_type="dataset",
45
+ private=a.private, exist_ok=True)
46
+ api.upload_folder(folder_path=a.folder, repo_id=a.repo_id, repo_type="dataset",
47
+ path_in_repo=a.path_in_repo,
48
+ commit_message=a.commit, allow_patterns=a.allow_patterns)
49
+ print(f"OK → https://huggingface.co/datasets/{a.repo_id}")
50
+
51
+
52
+ if __name__ == "__main__":
53
+ main()
code/tools/qa_contact_sheets.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Planches de contact pour la revue qualitative de l'échantillon `qa_sample_hf.py`.
3
+
4
+ Deux familles de planches :
5
+
6
+ * `sheet_<dataset>_<palier>.png` — 50 cellules `target | source` côte à côte
7
+ (une par mosaïque échantillonnée) : on balaye d'un coup d'œil les erreurs de
8
+ placement, les mosaïques dégénérées (aplats), la sévérité de la dégradation.
9
+ * `targets_<dataset>.png` — les 50 targets seuls, en grille dense : c'est la vue
10
+ qui fait sauter aux yeux une **répétition** de peinture.
11
+
12
+ Chaque cellule porte les 8 premiers caractères de l'uuid → un doublon visuel se
13
+ retrouve dans `manifest.json`.
14
+ """
15
+ import argparse
16
+ from pathlib import Path
17
+
18
+ from PIL import Image, ImageDraw
19
+
20
+ # les `source.png` de L0_explode montent à 16128² (260 Mpx) → au-delà du garde-fou
21
+ # anti-« decompression bomb » de PIL, qui lèverait DecompressionBombError.
22
+ Image.MAX_IMAGE_PIXELS = None
23
+
24
+ TH = 190 # côté d'une vignette
25
+ PAD = 6
26
+ LAB = 13 # bande de label sous la cellule
27
+
28
+
29
+ def _thumb(p, size=TH):
30
+ im = Image.open(p).convert("RGB")
31
+ im.thumbnail((size, size), Image.LANCZOS)
32
+ bg = Image.new("RGB", (size, size), (245, 245, 245))
33
+ bg.paste(im, ((size - im.width) // 2, (size - im.height) // 2))
34
+ return bg
35
+
36
+
37
+ def sheet(mosaics, out, title, pair=True, cols=5):
38
+ """`pair=True` → cellule target|source ; sinon target seul (grille dense)."""
39
+ cw = TH * 2 + PAD if pair else TH
40
+ ch = TH + LAB
41
+ rows = (len(mosaics) + cols - 1) // cols
42
+ W = cols * (cw + PAD) + PAD
43
+ H = rows * (ch + PAD) + PAD + 26
44
+ sh = Image.new("RGB", (W, H), (255, 255, 255))
45
+ d = ImageDraw.Draw(sh)
46
+ d.text((PAD, 8), title, fill=(0, 0, 0))
47
+
48
+ for i, m in enumerate(sorted(mosaics)):
49
+ x = PAD + (i % cols) * (cw + PAD)
50
+ y = 26 + PAD + (i // cols) * (ch + PAD)
51
+ try:
52
+ sh.paste(_thumb(m / "target.png"), (x, y))
53
+ if pair and (m / "source.png").exists():
54
+ sh.paste(_thumb(m / "source.png"), (x + TH + PAD, y))
55
+ except (FileNotFoundError, OSError) as e:
56
+ d.text((x + 4, y + 4), f"ERR {e.__class__.__name__}", fill=(200, 0, 0))
57
+ d.text((x + 2, y + TH + 1), m.name.replace("mosaic_", "")[:8], fill=(90, 90, 90))
58
+ out.parent.mkdir(parents=True, exist_ok=True)
59
+ sh.save(out)
60
+ return out
61
+
62
+
63
+ def main():
64
+ p = argparse.ArgumentParser()
65
+ p.add_argument("--sample", default="output/qa_sample")
66
+ p.add_argument("--out", default="output/qa_sheets")
67
+ a = p.parse_args()
68
+ root, out = Path(a.sample), Path(a.out)
69
+
70
+ paliers = sorted({d.name for d in root.glob("*/*/L*") if d.is_dir()})
71
+ datasets = sorted({f"{d.parent.name}/{d.name}" for d in root.glob("*/k*") if d.is_dir()})
72
+
73
+ for ds in datasets:
74
+ tag = ds.replace("/", "_")
75
+ for L in paliers:
76
+ mos = [m for m in (root / ds / L).iterdir() if m.is_dir()] \
77
+ if (root / ds / L).is_dir() else []
78
+ if not mos:
79
+ continue
80
+ o = sheet(mos, out / f"sheet_{tag}_{L}.png", f"{ds} {L} ({len(mos)} mosaïques — gauche: target / droite: source)")
81
+ print("[sheet]", o)
82
+ # vue « répétitions » : targets seuls, pris sur le premier palier dispo
83
+ for L in paliers:
84
+ mos = [m for m in (root / ds / L).iterdir() if m.is_dir()] \
85
+ if (root / ds / L).is_dir() else []
86
+ if mos:
87
+ o = sheet(mos, out / f"targets_{tag}.png",
88
+ f"{ds} — targets seuls ({len(mos)}) — repérage des répétitions",
89
+ pair=False, cols=10)
90
+ print("[targets]", o)
91
+ break
92
+
93
+
94
+ if __name__ == "__main__":
95
+ main()
code/tools/qa_overlays.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Overlays de contrôle sur l'échantillon : YOLO-Seg + reco-B.
3
+
4
+ Pour chaque (dataset, palier) de `output/qa_sample`, prend la **même** mosaïque
5
+ (uuid partagé par tous les paliers → comparaison L0→L4 à contenu constant) et
6
+ écrit dans le dossier de la mosaïque :
7
+
8
+ * `source_yolo_viz.png` — polygones `source_yolo.txt` repeints sur `source.png`
9
+ (contrôle : les masques collent-ils aux fragments ? la normalisation par le
10
+ canvas agrandi est-elle correcte ?)
11
+ * `recob_viz.png` — perte de dégradation (hachures grises) vs perte d'encodage
12
+ reco-B (hachures couleur), en repère target.
13
+
14
+ Les copies sont rassemblées à plat dans `--out` pour la revue.
15
+ """
16
+ import argparse
17
+ import shutil
18
+ import sys
19
+ from pathlib import Path
20
+
21
+ from PIL import Image
22
+
23
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "mosaic2fragments"))
24
+ Image.MAX_IMAGE_PIXELS = None # L0 monte à 260 Mpx (cf. qa_contact_sheets)
25
+
26
+ import visualize # noqa: E402
27
+
28
+
29
+ def main():
30
+ p = argparse.ArgumentParser()
31
+ p.add_argument("--sample", default="output/qa_sample")
32
+ p.add_argument("--out", default="output/qa_overlays")
33
+ p.add_argument("--per-cell", type=int, default=1, help="mosaïques par dataset×palier")
34
+ a = p.parse_args()
35
+ root, out = Path(a.sample), Path(a.out)
36
+ out.mkdir(parents=True, exist_ok=True)
37
+
38
+ cells = sorted(d for d in root.glob("*/k*/L*") if d.is_dir())
39
+ for c in cells:
40
+ tag = "_".join(c.parts[-3:])
41
+ for m in sorted(d for d in c.iterdir() if d.is_dir())[:a.per_cell]:
42
+ try:
43
+ visualize.visualize(m)
44
+ visualize.visualize_recob(m)
45
+ except Exception as e: # noqa: BLE001
46
+ print(f"✗ {tag}/{m.name[:14]} : {type(e).__name__}: {e}", flush=True)
47
+ continue
48
+ for f, suf in (("source_yolo_viz.png", "yolo"), ("recob_viz.png", "recob")):
49
+ if (m / f).exists():
50
+ shutil.copy(m / f, out / f"{suf}_{tag}_{m.name[7:15]}.png")
51
+ print(f"✓ {tag}/{m.name[7:15]}", flush=True)
52
+
53
+
54
+ if __name__ == "__main__":
55
+ main()
code/tools/qa_sample_hf.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Échantillonne ~1 % de chaque dataset publié sur le Hub, **sans télécharger les tars**.
3
+
4
+ Un `.tar.gz` n'est pas seekable : on ne peut pas atteindre un membre au milieu
5
+ sans décompresser tout ce qui précède. On lit donc le flux HTTP au fil de l'eau
6
+ (`tarfile` mode `r|gz`) et on **coupe la connexion** dès que N dossiers
7
+ `mosaic_<uuid>/` ont été vus → on ne transfère que ~N/5000 des octets.
8
+
9
+ ⚠️ Biais assumé : l'échantillon est un *préfixe* de l'archive. Les noms étant des
10
+ uuid4, il est non biaisé vis-à-vis du **contenu** des peintures, mais il suit
11
+ l'ordre de création des dossiers (donc l'ordre de génération).
12
+
13
+ Les crops `fragments/*.png` sont ignorés (inutiles à la revue visuelle, ~la
14
+ moitié du volume disque).
15
+ """
16
+ import argparse
17
+ import concurrent.futures as cf
18
+ import io
19
+ import json
20
+ import tarfile
21
+ from pathlib import Path
22
+
23
+ import requests
24
+ from huggingface_hub import get_token, hf_hub_url
25
+
26
+ REPO = "<user>/<dataset-repo>" # défaut ; surchargeable par --repo-id
27
+ DATASETS = [f"{g}/{k}" for g in ("poly_balanced", "mono_compact")
28
+ for k in ("k02", "k03", "k05", "k10-15")]
29
+ PALIERS = ["L0_explode", "L1_translation", "L2_rotation", "L3_light", "L4_strong"]
30
+ KEEP = {"target.png", "source.png", "source_yolo.txt", "graph_fragments.json",
31
+ "graph_complete.json", "gt_layout.json", "degradation.md", "gnn_ready.npz"}
32
+
33
+
34
+ def sample_one(ds, palier, n, out_root, repo):
35
+ """Extrait les `n` premières mosaïques de `<ds>/<palier>.tar.gz`. → (dl_bytes, uuids)"""
36
+ url = hf_hub_url(repo, f"{ds}/{palier}.tar.gz", repo_type="dataset")
37
+ tok = get_token()
38
+ hdr = {"Authorization": f"Bearer {tok}"} if tok else {}
39
+ dest = Path(out_root) / ds / palier
40
+ dest.mkdir(parents=True, exist_ok=True)
41
+
42
+ seen, done = [], False
43
+ with requests.get(url, headers=hdr, stream=True, timeout=120) as r:
44
+ r.raise_for_status()
45
+ raw = r.raw # urllib3, décompression gzip faite par tarfile
46
+ counted = _Counter(raw)
47
+ try:
48
+ with tarfile.open(fileobj=counted, mode="r|gz") as tf:
49
+ for m in tf:
50
+ parts = m.name.split("/")
51
+ # `tar` sous macOS embarque des AppleDouble `._x` (xattrs) : à jeter.
52
+ # Et l'archive liste d'abord les 5000 répertoires, PUIS les fichiers
53
+ # groupés par mosaïque → on compte les uuid sur les fichiers utiles.
54
+ if any(c.startswith("._") for c in parts):
55
+ continue
56
+ if len(parts) != 3 or not m.isfile() or parts[-1] not in KEEP:
57
+ continue
58
+ uid = parts[1]
59
+ if uid not in seen:
60
+ if len(seen) >= n: # on entre dans la (n+1)-ème → stop
61
+ done = True
62
+ break
63
+ seen.append(uid)
64
+ tgt = dest / uid / parts[-1]
65
+ tgt.parent.mkdir(parents=True, exist_ok=True)
66
+ tgt.write_bytes(tf.extractfile(m).read())
67
+ except (tarfile.ReadError, OSError) as e:
68
+ if not done:
69
+ raise RuntimeError(f"{ds}/{palier}: {e}") from e
70
+ return counted.n, seen
71
+
72
+
73
+ class _Counter(io.RawIOBase):
74
+ """Wrapper qui compte les octets réellement transférés."""
75
+
76
+ def __init__(self, raw):
77
+ self.raw, self.n = raw, 0
78
+
79
+ def read(self, size=-1):
80
+ b = self.raw.read(size)
81
+ self.n += len(b)
82
+ return b
83
+
84
+ def readable(self):
85
+ return True
86
+
87
+
88
+ def main():
89
+ p = argparse.ArgumentParser()
90
+ p.add_argument("--n", type=int, default=50, help="mosaïques par palier (1%% de 5000)")
91
+ p.add_argument("--out", default="output/qa_sample")
92
+ p.add_argument("--repo-id", default=REPO)
93
+ p.add_argument("--jobs", type=int, default=6)
94
+ a = p.parse_args()
95
+
96
+ jobs = [(ds, L) for ds in DATASETS for L in PALIERS]
97
+ manifest, total = {}, 0
98
+ with cf.ThreadPoolExecutor(a.jobs) as ex:
99
+ futs = {ex.submit(sample_one, ds, L, a.n, a.out, a.repo_id): (ds, L)
100
+ for ds, L in jobs}
101
+ for i, f in enumerate(cf.as_completed(futs), 1):
102
+ ds, L = futs[f]
103
+ try:
104
+ nb, uids = f.result()
105
+ except Exception as e: # noqa: BLE001 — on veut la suite
106
+ print(f"[{i:2d}/40] ✗ {ds}/{L} : {e}", flush=True)
107
+ continue
108
+ total += nb
109
+ manifest[f"{ds}/{L}"] = uids
110
+ print(f"[{i:2d}/40] ✓ {ds}/{L} : {len(uids)} mosaïques, {nb/1e6:.0f} Mo",
111
+ flush=True)
112
+
113
+ Path(a.out).mkdir(parents=True, exist_ok=True)
114
+ (Path(a.out) / "manifest.json").write_text(json.dumps(manifest, indent=1))
115
+ print(f"\nTotal transféré : {total/1e9:.2f} Go → {a.out}")
116
+
117
+
118
+ if __name__ == "__main__":
119
+ main()