Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20261013T022035Z-pbisc-red-scsemi-blue/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/data/method_palette_20261013/palette.json +306 -0
- paper-releases/pbisc-diffusion/updates/20261013T022035Z-pbisc-red-scsemi-blue/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/data/style_review_20261013/slide_13.png +3 -0
- paper-releases/pbisc-diffusion/updates/20261013T022035Z-pbisc-red-scsemi-blue/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/review_palette_pdf.py +382 -0
- paper-releases/pbisc-diffusion/updates/20261013T022035Z-pbisc-red-scsemi-blue/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/verify_review_palette.py +54 -0
paper-releases/pbisc-diffusion/updates/20261013T022035Z-pbisc-red-scsemi-blue/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/data/method_palette_20261013/palette.json
ADDED
|
@@ -0,0 +1,306 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema": "pbisc.method-palette.v1",
|
| 3 |
+
"user_directive": "PBISC red family, scSemiProfiler blue family throughout current results review",
|
| 4 |
+
"primary": {
|
| 5 |
+
"PBISC": "#B2182B",
|
| 6 |
+
"scSemiProfiler": "#2166AC"
|
| 7 |
+
},
|
| 8 |
+
"rules": {
|
| 9 |
+
"fig1b_overview_nature": {
|
| 10 |
+
"mapping": {
|
| 11 |
+
"#5B6E8F": "#B2182B",
|
| 12 |
+
"#E6EAF1": "#F8E8EB",
|
| 13 |
+
"#A5AFC1": "#D5808A",
|
| 14 |
+
"#8E6C9E": "#9E1B32"
|
| 15 |
+
},
|
| 16 |
+
"reason": "PBISC model blocks, model arrows and optional adaptation only; preserve expression, detection, bulk and cell-type encodings.",
|
| 17 |
+
"source_pdf": "/home/sj_server_1/PBISC/paper-release-20260928/manuscript/figures/fig01_architecture_nature.pdf"
|
| 18 |
+
},
|
| 19 |
+
"sec02_bulk_conditioning": {
|
| 20 |
+
"mapping": {},
|
| 21 |
+
"reason": "Orange denotes bulk-conditioning/context, not a method comparison; preserve semantic diagram colors."
|
| 22 |
+
},
|
| 23 |
+
"fig1d_corpus": {
|
| 24 |
+
"mapping": {},
|
| 25 |
+
"reason": "Cell types and cohort composition, not method colors."
|
| 26 |
+
},
|
| 27 |
+
"review_style_20261013_ablation": {
|
| 28 |
+
"mapping": {
|
| 29 |
+
"#D55E00": "#B2182B",
|
| 30 |
+
"#009E73": "#E57F88",
|
| 31 |
+
"#332288": "#7F0000",
|
| 32 |
+
"#0072B2": "#D96874",
|
| 33 |
+
"#A6CBE3": "#F1A6AE",
|
| 34 |
+
"#882255": "#8F2638"
|
| 35 |
+
},
|
| 36 |
+
"reason": "PBISC architecture and gene-panel variants; black real-R2 reference retained."
|
| 37 |
+
},
|
| 38 |
+
"sec03_panel": {
|
| 39 |
+
"mapping": {
|
| 40 |
+
"#D55E00": "#B2182B",
|
| 41 |
+
"#E69F00": "#2166AC",
|
| 42 |
+
"#0072B2": "#D96874",
|
| 43 |
+
"#A6CBE3": "#F1A6AE",
|
| 44 |
+
"#882255": "#8F2638"
|
| 45 |
+
},
|
| 46 |
+
"reason": "PBISC gene panels in red shades; scSemi reference line blue."
|
| 47 |
+
},
|
| 48 |
+
"review_style_20261013_rank": {
|
| 49 |
+
"mapping": {
|
| 50 |
+
"#E07B39": "#7F0000",
|
| 51 |
+
"#D55E00": "#B2182B"
|
| 52 |
+
},
|
| 53 |
+
"reason": "Full fine-tuning dark red and LoRA red; rank markers preserve their shapes."
|
| 54 |
+
},
|
| 55 |
+
"fig3_healthy_pairs": {
|
| 56 |
+
"mapping": {
|
| 57 |
+
"#D55E00": "#B2182B",
|
| 58 |
+
"#E69F00": "#2166AC",
|
| 59 |
+
"#A6CBE3": "#F1A6AE",
|
| 60 |
+
"#0072B2": "#D96874"
|
| 61 |
+
},
|
| 62 |
+
"reason": "PBISC and its raw/calibrated inputs in red shades; scSemi blue. Neutral reference/errorbar styles retained."
|
| 63 |
+
},
|
| 64 |
+
"fig3_healthy_fewpair": {
|
| 65 |
+
"mapping": {
|
| 66 |
+
"#D55E00": "#B2182B",
|
| 67 |
+
"#E69F00": "#2166AC",
|
| 68 |
+
"#A6CBE3": "#F1A6AE",
|
| 69 |
+
"#0072B2": "#D96874"
|
| 70 |
+
},
|
| 71 |
+
"reason": "PBISC and its raw/calibrated inputs in red shades; scSemi blue. Neutral reference/errorbar styles retained."
|
| 72 |
+
},
|
| 73 |
+
"fig3_healthy_copy": {
|
| 74 |
+
"mapping": {
|
| 75 |
+
"#D55E00": "#B2182B",
|
| 76 |
+
"#E69F00": "#2166AC",
|
| 77 |
+
"#A6CBE3": "#F1A6AE",
|
| 78 |
+
"#0072B2": "#D96874"
|
| 79 |
+
},
|
| 80 |
+
"reason": "PBISC and its raw/calibrated inputs in red shades; scSemi blue. Neutral reference/errorbar styles retained."
|
| 81 |
+
},
|
| 82 |
+
"fig2_healthy_pairs": {
|
| 83 |
+
"mapping": {
|
| 84 |
+
"#D55E00": "#B2182B",
|
| 85 |
+
"#E69F00": "#2166AC",
|
| 86 |
+
"#A6CBE3": "#F1A6AE",
|
| 87 |
+
"#0072B2": "#D96874"
|
| 88 |
+
},
|
| 89 |
+
"reason": "PBISC and its raw/calibrated inputs in red shades; scSemi blue. Neutral reference/errorbar styles retained."
|
| 90 |
+
},
|
| 91 |
+
"fig4_disease_fewpair": {
|
| 92 |
+
"mapping": {
|
| 93 |
+
"#D55E00": "#B2182B",
|
| 94 |
+
"#E69F00": "#2166AC",
|
| 95 |
+
"#A6CBE3": "#F1A6AE",
|
| 96 |
+
"#0072B2": "#D96874"
|
| 97 |
+
},
|
| 98 |
+
"reason": "PBISC and its raw/calibrated inputs in red shades; scSemi blue. Neutral reference/errorbar styles retained."
|
| 99 |
+
},
|
| 100 |
+
"sec09_fewpair_cells": {
|
| 101 |
+
"mapping": {
|
| 102 |
+
"#D55E00": "#B2182B",
|
| 103 |
+
"#E69F00": "#2166AC",
|
| 104 |
+
"#A6CBE3": "#F1A6AE",
|
| 105 |
+
"#0072B2": "#D96874"
|
| 106 |
+
},
|
| 107 |
+
"reason": "PBISC and its raw/calibrated inputs in red shades; scSemi blue. Neutral reference/errorbar styles retained."
|
| 108 |
+
},
|
| 109 |
+
"sec09_extra_ksens": {
|
| 110 |
+
"mapping": {
|
| 111 |
+
"#D55E00": "#B2182B",
|
| 112 |
+
"#E69F00": "#2166AC",
|
| 113 |
+
"#A6CBE3": "#F1A6AE",
|
| 114 |
+
"#0072B2": "#D96874"
|
| 115 |
+
},
|
| 116 |
+
"reason": "PBISC and its raw/calibrated inputs in red shades; scSemi blue. Neutral reference/errorbar styles retained."
|
| 117 |
+
},
|
| 118 |
+
"sec09_same_pairs": {
|
| 119 |
+
"mapping": {
|
| 120 |
+
"#D55E00": "#B2182B",
|
| 121 |
+
"#E69F00": "#2166AC",
|
| 122 |
+
"#A6CBE3": "#F1A6AE",
|
| 123 |
+
"#0072B2": "#D96874"
|
| 124 |
+
},
|
| 125 |
+
"reason": "PBISC and its raw/calibrated inputs in red shades; scSemi blue. Neutral reference/errorbar styles retained."
|
| 126 |
+
},
|
| 127 |
+
"sec04_sle_benchmark": {
|
| 128 |
+
"mapping": {
|
| 129 |
+
"#D55E00": "#B2182B",
|
| 130 |
+
"#E69F00": "#2166AC",
|
| 131 |
+
"#A6CBE3": "#F1A6AE",
|
| 132 |
+
"#0072B2": "#D96874"
|
| 133 |
+
},
|
| 134 |
+
"reason": "PBISC and its raw/calibrated inputs in red shades; scSemi blue. Neutral reference/errorbar styles retained."
|
| 135 |
+
},
|
| 136 |
+
"review_style_20261013_healthy_composition": {
|
| 137 |
+
"mapping": {
|
| 138 |
+
"#D55E00": "#B2182B",
|
| 139 |
+
"#0072B2": "#2166AC"
|
| 140 |
+
},
|
| 141 |
+
"reason": "Two-method paired comparison; this asset already used blue for scSemi."
|
| 142 |
+
},
|
| 143 |
+
"sec05_condition_space": {
|
| 144 |
+
"mapping": {},
|
| 145 |
+
"reason": "Input-space diagnostic: measured/shift-corrected inputs, no method comparison."
|
| 146 |
+
},
|
| 147 |
+
"sec09_time_to_apply": {
|
| 148 |
+
"mapping": {
|
| 149 |
+
"#D55E00": "#B2182B",
|
| 150 |
+
"#E69F00": "#2166AC",
|
| 151 |
+
"#F2B48C": "#F1B4BC",
|
| 152 |
+
"#F5D08A": "#67A9CF"
|
| 153 |
+
},
|
| 154 |
+
"reason": "PBISC adaptation/generation red shades; scSemi training/inference blue shades."
|
| 155 |
+
},
|
| 156 |
+
"sec09_cohorts": {
|
| 157 |
+
"mapping": {},
|
| 158 |
+
"reason": "Cohort metadata table, no method colors."
|
| 159 |
+
},
|
| 160 |
+
"fig4_disease_fivefold": {
|
| 161 |
+
"mapping": {
|
| 162 |
+
"#D55E00": "#B2182B",
|
| 163 |
+
"#E69F00": "#2166AC",
|
| 164 |
+
"#A6CBE3": "#F1A6AE",
|
| 165 |
+
"#0072B2": "#D96874",
|
| 166 |
+
"#CC79A7": "#8F4666"
|
| 167 |
+
},
|
| 168 |
+
"reason": "PBISC LoRA, zero-shot/calibrated and sc-only fine-tuning red family; scSemi blue."
|
| 169 |
+
},
|
| 170 |
+
"sec09_cat_curves": {
|
| 171 |
+
"mapping": {
|
| 172 |
+
"#D55E00": "#B2182B",
|
| 173 |
+
"#E69F00": "#2166AC",
|
| 174 |
+
"#A6CBE3": "#F1A6AE",
|
| 175 |
+
"#0072B2": "#D96874",
|
| 176 |
+
"#CC79A7": "#8F4666"
|
| 177 |
+
},
|
| 178 |
+
"reason": "PBISC LoRA, zero-shot/calibrated and sc-only fine-tuning red family; scSemi blue."
|
| 179 |
+
},
|
| 180 |
+
"secS_deconv_disease": {
|
| 181 |
+
"mapping": {
|
| 182 |
+
"#D55E00": "#B2182B",
|
| 183 |
+
"#E69F00": "#2166AC",
|
| 184 |
+
"#CC79A7": "#6A51A3"
|
| 185 |
+
},
|
| 186 |
+
"reason": "PBISC red, scSemi blue where present; CIBERSORTx purple and BayesPrism green."
|
| 187 |
+
},
|
| 188 |
+
"secS_deconv_composition": {
|
| 189 |
+
"mapping": {
|
| 190 |
+
"#D55E00": "#B2182B",
|
| 191 |
+
"#E69F00": "#2166AC",
|
| 192 |
+
"#CC79A7": "#6A51A3"
|
| 193 |
+
},
|
| 194 |
+
"reason": "PBISC red, scSemi blue where present; CIBERSORTx purple and BayesPrism green."
|
| 195 |
+
},
|
| 196 |
+
"review_style_20261013_rare_observed": {
|
| 197 |
+
"mapping": {},
|
| 198 |
+
"reason": "Observed-frequency heatmap encodes abundance, not a method."
|
| 199 |
+
},
|
| 200 |
+
"review_style_20261013_rare_corrected_comparison": {
|
| 201 |
+
"mapping": {},
|
| 202 |
+
"reason": "Points encode cohorts; x/y axes explicitly name methods. Preserve cohort color legend."
|
| 203 |
+
},
|
| 204 |
+
"review_style_20261013_behcet": {
|
| 205 |
+
"mapping": {
|
| 206 |
+
"#0072B2": "#D96874",
|
| 207 |
+
"#D55E00": "#B2182B"
|
| 208 |
+
},
|
| 209 |
+
"reason": "PBISC raw/calibrated and LoRA predictions in red family; observed native/depth-matched references black."
|
| 210 |
+
},
|
| 211 |
+
"sec05_cells_umap": {
|
| 212 |
+
"mapping": {},
|
| 213 |
+
"reason": "UMAP points and legend encode cell types. Preserve images and biological labels."
|
| 214 |
+
},
|
| 215 |
+
"sec05_cells_metrics": {
|
| 216 |
+
"mapping": {
|
| 217 |
+
"#A6CBE3": "#F1A6AE",
|
| 218 |
+
"#5E8FB5": "#D96874"
|
| 219 |
+
},
|
| 220 |
+
"reason": "Raw-bulk and pseudobulk-input PBISC reconstructions red; observed real cells grey. Scope black replacement to four verified rectangles only.",
|
| 221 |
+
"rectangle_rules": [
|
| 222 |
+
{
|
| 223 |
+
"rect": [
|
| 224 |
+
66.389,
|
| 225 |
+
247.078,
|
| 226 |
+
91.925,
|
| 227 |
+
361.296
|
| 228 |
+
],
|
| 229 |
+
"old": "#1A1A1A",
|
| 230 |
+
"new": "#B2182B"
|
| 231 |
+
},
|
| 232 |
+
{
|
| 233 |
+
"rect": [
|
| 234 |
+
207.736,
|
| 235 |
+
98.028,
|
| 236 |
+
233.272,
|
| 237 |
+
361.296
|
| 238 |
+
],
|
| 239 |
+
"old": "#1A1A1A",
|
| 240 |
+
"new": "#B2182B"
|
| 241 |
+
},
|
| 242 |
+
{
|
| 243 |
+
"rect": [
|
| 244 |
+
349.082,
|
| 245 |
+
217.017,
|
| 246 |
+
374.618,
|
| 247 |
+
361.296
|
| 248 |
+
],
|
| 249 |
+
"old": "#1A1A1A",
|
| 250 |
+
"new": "#B2182B"
|
| 251 |
+
},
|
| 252 |
+
{
|
| 253 |
+
"rect": [
|
| 254 |
+
172.368,
|
| 255 |
+
8.734,
|
| 256 |
+
185.568,
|
| 257 |
+
17.134
|
| 258 |
+
],
|
| 259 |
+
"old": "#1A1A1A",
|
| 260 |
+
"new": "#B2182B"
|
| 261 |
+
}
|
| 262 |
+
]
|
| 263 |
+
},
|
| 264 |
+
"sec08_cross_cohort": {
|
| 265 |
+
"mapping": {
|
| 266 |
+
"#A6CBE3": "#F1A6AE",
|
| 267 |
+
"#0072B2": "#D96874",
|
| 268 |
+
"#44AA99": "#E57F88",
|
| 269 |
+
"#117733": "#8F2638",
|
| 270 |
+
"#332288": "#5F0F24",
|
| 271 |
+
"#D55E00": "#B2182B"
|
| 272 |
+
},
|
| 273 |
+
"reason": "All PBISC adaptation/cohort variants in distinct red shades; existing line styles preserved."
|
| 274 |
+
},
|
| 275 |
+
"sec08_cross_cohort_steps": {
|
| 276 |
+
"mapping": {
|
| 277 |
+
"#A6CBE3": "#F1A6AE",
|
| 278 |
+
"#0072B2": "#D96874",
|
| 279 |
+
"#44AA99": "#E57F88",
|
| 280 |
+
"#117733": "#8F2638",
|
| 281 |
+
"#332288": "#5F0F24",
|
| 282 |
+
"#D55E00": "#B2182B"
|
| 283 |
+
},
|
| 284 |
+
"reason": "All PBISC adaptation/cohort variants in distinct red shades; existing line styles preserved."
|
| 285 |
+
},
|
| 286 |
+
"sec07_no_pretraining": {
|
| 287 |
+
"mapping": {
|
| 288 |
+
"#D55E00": "#B2182B",
|
| 289 |
+
"#882255": "#7F0000",
|
| 290 |
+
"#0072B2": "#D96874"
|
| 291 |
+
},
|
| 292 |
+
"reason": "Pretrained LoRA red, same-architecture scratch ablation dark red, zero-shot rose."
|
| 293 |
+
},
|
| 294 |
+
"secA_scsemi_readout": {
|
| 295 |
+
"mapping": {
|
| 296 |
+
"#D55E00": "#B2182B",
|
| 297 |
+
"#E69F00": "#2166AC",
|
| 298 |
+
"#F5D08A": "#67A9CF"
|
| 299 |
+
},
|
| 300 |
+
"reason": "PBISC red; official scSemi blue and modified readout pale blue with original hatch."
|
| 301 |
+
}
|
| 302 |
+
},
|
| 303 |
+
"reference_policy": "Biological/cohort colors and neutral observed/oracle diagnostic references are separate encodings, not model identity.",
|
| 304 |
+
"unused_fill_policy": "Matplotlib #1F77B4 fill on neutral errorbar caps is not painted; preserve.",
|
| 305 |
+
"preserve_geometry_text_data": true
|
| 306 |
+
}
|
paper-releases/pbisc-diffusion/updates/20261013T022035Z-pbisc-red-scsemi-blue/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/data/style_review_20261013/slide_13.png
ADDED
|
Git LFS Details
|
paper-releases/pbisc-diffusion/updates/20261013T022035Z-pbisc-red-scsemi-blue/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/review_palette_pdf.py
ADDED
|
@@ -0,0 +1,382 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Change explicit RGB plot colours while preserving a PDF's scientific content.
|
| 2 |
+
|
| 3 |
+
This module edits vector paint instructions, never raster pixels. Callers must
|
| 4 |
+
provide a figure-specific semantic mapping: the same RGB can mean a method,
|
| 5 |
+
cell type, cohort or gene panel in different figures.
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import hashlib
|
| 10 |
+
import json
|
| 11 |
+
import math
|
| 12 |
+
import os
|
| 13 |
+
import re
|
| 14 |
+
import tempfile
|
| 15 |
+
from collections import Counter
|
| 16 |
+
from decimal import Decimal
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
import fitz
|
| 20 |
+
import pikepdf
|
| 21 |
+
|
| 22 |
+
RGB_TOLERANCE = 1e-8
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _file_sha(path: Path) -> str:
|
| 26 |
+
with path.open("rb") as handle:
|
| 27 |
+
return hashlib.file_digest(handle, "sha256").hexdigest()
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _hex(value: str) -> str:
|
| 31 |
+
if not isinstance(value, str) or not re.fullmatch(r"#?[0-9a-fA-F]{6}", value):
|
| 32 |
+
raise ValueError(f"Expected a six-digit RGB hex colour: {value!r}")
|
| 33 |
+
return "#" + value.removeprefix("#").upper()
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _rgb(value: str) -> tuple[float, float, float]:
|
| 37 |
+
return tuple(int(value[i:i + 2], 16) / 255 for i in (1, 3, 5))
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _value(value):
|
| 41 |
+
"""Stable parsed operand representation, independent of PDF object numbers."""
|
| 42 |
+
if value is None or isinstance(value, (str, bool)):
|
| 43 |
+
return value
|
| 44 |
+
if isinstance(value, (int, float, Decimal)):
|
| 45 |
+
return ["number", str(Decimal(str(value)).normalize())]
|
| 46 |
+
kind = getattr(value, "_type_name", "")
|
| 47 |
+
if kind == "string":
|
| 48 |
+
return ["string", bytes(value).hex()]
|
| 49 |
+
if kind == "name":
|
| 50 |
+
return ["name", str(value)]
|
| 51 |
+
if kind == "array" or isinstance(value, (list, tuple)):
|
| 52 |
+
return ["array", [_value(item) for item in value]]
|
| 53 |
+
if kind == "dictionary":
|
| 54 |
+
return ["dictionary", sorted((str(key), _value(item)) for key, item in value.items())]
|
| 55 |
+
if kind == "stream":
|
| 56 |
+
# Used for image colour-space lookup streams, not as content operands.
|
| 57 |
+
return ["stream", hashlib.sha256(value.read_bytes()).hexdigest()]
|
| 58 |
+
raise ValueError(f"Unsupported PDF operand type: {kind or type(value).__name__}")
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _fingerprint(instructions, *, ignore_rgb: bool) -> str:
|
| 62 |
+
rows = []
|
| 63 |
+
for instruction in instructions:
|
| 64 |
+
if isinstance(instruction, pikepdf.ContentStreamInlineImage):
|
| 65 |
+
# These figures use image XObjects. Fail instead of accidentally
|
| 66 |
+
# reserializing an unsupported inline raster payload.
|
| 67 |
+
raise ValueError("Inline-image content is unsupported; retain the original PDF")
|
| 68 |
+
op = str(instruction.operator)
|
| 69 |
+
operands = instruction.operands
|
| 70 |
+
value = ["unchanged-rgb-slot"] if ignore_rgb and op in {"rg", "RG"} else _value(list(operands))
|
| 71 |
+
rows.append([op, value])
|
| 72 |
+
return hashlib.sha256(json.dumps(rows, separators=(",", ":"), ensure_ascii=True).encode()).hexdigest()
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _content_streams(pdf: pikepdf.Pdf) -> list[tuple[str, object]]:
|
| 76 |
+
"""Traverse page contents, nested Forms and coloured tiling patterns once."""
|
| 77 |
+
found = []
|
| 78 |
+
seen = set()
|
| 79 |
+
resource_seen = set()
|
| 80 |
+
# Direct pikepdf dictionary wrappers have objgen=(0, 0). Keep them alive
|
| 81 |
+
# until traversal ends so Python cannot recycle id(wrapper) for a different
|
| 82 |
+
# resource dictionary and incorrectly classify it as already visited.
|
| 83 |
+
resource_wrappers = []
|
| 84 |
+
|
| 85 |
+
def identity(obj):
|
| 86 |
+
pair = tuple(obj.objgen)
|
| 87 |
+
return pair if pair != (0, 0) else ("direct", id(obj))
|
| 88 |
+
|
| 89 |
+
def content(stream, label):
|
| 90 |
+
key = identity(stream)
|
| 91 |
+
if key in seen:
|
| 92 |
+
return
|
| 93 |
+
seen.add(key)
|
| 94 |
+
found.append((label, stream))
|
| 95 |
+
resources(stream.get("/Resources", {}), label)
|
| 96 |
+
|
| 97 |
+
def resources(res, label):
|
| 98 |
+
resource_wrappers.append(res)
|
| 99 |
+
key = identity(res) if hasattr(res, "objgen") else ("dict", id(res))
|
| 100 |
+
if key in resource_seen:
|
| 101 |
+
return
|
| 102 |
+
resource_seen.add(key)
|
| 103 |
+
for name, obj in sorted(res.get("/XObject", {}).items(), key=lambda pair: str(pair[0])):
|
| 104 |
+
if obj.get("/Subtype") == "/Form":
|
| 105 |
+
content(obj, f"{label}/XObject/{name}")
|
| 106 |
+
for name, obj in sorted(res.get("/Pattern", {}).items(), key=lambda pair: str(pair[0])):
|
| 107 |
+
if obj.get("/PatternType") == 1 and obj.get("/PaintType") == 1:
|
| 108 |
+
content(obj, f"{label}/Pattern/{name}")
|
| 109 |
+
|
| 110 |
+
for index, page in enumerate(pdf.pages):
|
| 111 |
+
contents = page.obj.get("/Contents")
|
| 112 |
+
if contents is not None:
|
| 113 |
+
streams = list(contents) if getattr(contents, "_type_name", "") == "array" else [contents]
|
| 114 |
+
for number, stream in enumerate(streams):
|
| 115 |
+
content(stream, f"page{index}/Contents{number}")
|
| 116 |
+
resources(page.obj.get("/Resources", {}), f"page{index}")
|
| 117 |
+
return found
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def _image_payloads(pdf: pikepdf.Pdf) -> list[dict]:
|
| 121 |
+
images = []
|
| 122 |
+
for obj in pdf.objects:
|
| 123 |
+
if getattr(obj, "_type_name", "") != "stream" or obj.get("/Subtype") != "/Image":
|
| 124 |
+
continue
|
| 125 |
+
images.append({
|
| 126 |
+
"decoded_sha256": hashlib.sha256(obj.read_bytes()).hexdigest(),
|
| 127 |
+
"width": int(obj.get("/Width", 0)), "height": int(obj.get("/Height", 0)),
|
| 128 |
+
"bits_per_component": int(obj.get("/BitsPerComponent", 0)),
|
| 129 |
+
"colour_space": _value(obj.get("/ColorSpace")),
|
| 130 |
+
"decode": _value(obj.get("/Decode")),
|
| 131 |
+
"image_mask": bool(obj.get("/ImageMask", False)),
|
| 132 |
+
})
|
| 133 |
+
return sorted(images, key=lambda item: json.dumps(item, sort_keys=True))
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def _geometry(path: Path) -> list[dict]:
|
| 137 |
+
"""Keep every extracted character/font/position and page box, excluding RGB."""
|
| 138 |
+
records = []
|
| 139 |
+
with fitz.open(path) as document:
|
| 140 |
+
for page in document:
|
| 141 |
+
raw = page.get_text("rawdict", flags=fitz.TEXTFLAGS_RAWDICT & ~fitz.TEXT_PRESERVE_IMAGES)
|
| 142 |
+
for block in raw.get("blocks", []):
|
| 143 |
+
for line in block.get("lines", []):
|
| 144 |
+
for span in line.get("spans", []):
|
| 145 |
+
span.pop("color", None)
|
| 146 |
+
records.append({"rect": list(page.rect), "mediabox": list(page.mediabox),
|
| 147 |
+
"cropbox": list(page.cropbox), "rotation": page.rotation,
|
| 148 |
+
"text_geometry": raw})
|
| 149 |
+
return records
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def _rectangle_matches(pdf, instructions, rules: list[dict], tolerance: float) -> dict[int, dict]:
|
| 153 |
+
"""Match explicit, filled-and-stroked page rectangles, never text or Forms.
|
| 154 |
+
|
| 155 |
+
This deliberately narrow path handles saved Matplotlib bar/legend patches.
|
| 156 |
+
Transformed, rotated, compound and curved paths are rejected as candidates.
|
| 157 |
+
"""
|
| 158 |
+
if len(pdf.pages) != 1:
|
| 159 |
+
raise ValueError("Scoped rectangle rules require a single-page PDF")
|
| 160 |
+
page = pdf.pages[0]
|
| 161 |
+
media = [float(value) for value in page.mediabox]
|
| 162 |
+
if (media[:2] != [0., 0.] or int(page.obj.get("/Rotate", 0)) != 0
|
| 163 |
+
or list(page.obj.get("/CropBox", page.mediabox)) != list(page.mediabox)):
|
| 164 |
+
raise ValueError("Scoped rectangles require unrotated, uncropped zero-origin page coordinates")
|
| 165 |
+
normalized = []
|
| 166 |
+
for rule in rules:
|
| 167 |
+
rect = [float(value) for value in rule["rect"]]
|
| 168 |
+
if (len(rect) != 4 or not all(math.isfinite(value) for value in rect)
|
| 169 |
+
or rect[2] <= rect[0] or rect[3] <= rect[1]):
|
| 170 |
+
raise ValueError("Invalid scoped rectangle")
|
| 171 |
+
normalized.append({"rect": rect, "old": _hex(rule["old"]), "new": _hex(rule["new"])})
|
| 172 |
+
fill = stroke = (0., 0., 0.)
|
| 173 |
+
transformed = False
|
| 174 |
+
stack, points, matches = [], [], {}
|
| 175 |
+
invalid_path = False
|
| 176 |
+
seen = Counter()
|
| 177 |
+
for index, instruction in enumerate(instructions):
|
| 178 |
+
op, values = str(instruction.operator), instruction.operands
|
| 179 |
+
if op == "q":
|
| 180 |
+
stack.append((fill, stroke, transformed))
|
| 181 |
+
elif op == "Q":
|
| 182 |
+
if not stack:
|
| 183 |
+
raise ValueError("Unbalanced PDF graphics state")
|
| 184 |
+
fill, stroke, transformed = stack.pop()
|
| 185 |
+
elif op == "cm":
|
| 186 |
+
transformed = transformed or tuple(float(value) for value in values) != (1., 0., 0., 1., 0., 0.)
|
| 187 |
+
elif op in {"g", "G", "rg", "RG", "k", "K", "sc", "SC", "scn", "SCN"}:
|
| 188 |
+
rgb = ((float(values[0]),) * 3 if op in {"g", "G"}
|
| 189 |
+
else tuple(float(value) for value in values) if op in {"rg", "RG"} else None)
|
| 190 |
+
if op in {"g", "rg", "k", "sc", "scn"}:
|
| 191 |
+
fill = rgb
|
| 192 |
+
else:
|
| 193 |
+
stroke = rgb
|
| 194 |
+
elif op == "m":
|
| 195 |
+
invalid_path = invalid_path or bool(points)
|
| 196 |
+
points.append(tuple(float(value) for value in values))
|
| 197 |
+
elif op == "l":
|
| 198 |
+
points.append(tuple(float(value) for value in values))
|
| 199 |
+
elif op == "re":
|
| 200 |
+
invalid_path = invalid_path or bool(points)
|
| 201 |
+
x, y, width, height = (float(value) for value in values)
|
| 202 |
+
points.extend([(x, y), (x + width, y), (x + width, y + height), (x, y + height)])
|
| 203 |
+
elif op in {"c", "v", "y"}:
|
| 204 |
+
invalid_path = True
|
| 205 |
+
elif op in {"B", "B*", "b", "b*", "f", "f*", "F", "S", "s", "n"}:
|
| 206 |
+
vertices = points[:-1] if len(points) == 5 and points[-1] == points[0] else points
|
| 207 |
+
if not transformed and not invalid_path and len(vertices) == 4 and op in {"B", "B*", "b", "b*"}:
|
| 208 |
+
xs, ys = sorted({point[0] for point in vertices}), sorted({point[1] for point in vertices})
|
| 209 |
+
axis_aligned = all(a[0] == b[0] or a[1] == b[1]
|
| 210 |
+
for a, b in zip(vertices, vertices[1:] + vertices[:1]))
|
| 211 |
+
if len(xs) == 2 and len(ys) == 2 and axis_aligned and len(set(vertices)) == 4:
|
| 212 |
+
rect = [xs[0], media[3] - ys[1], xs[1], media[3] - ys[0]]
|
| 213 |
+
for rule_index, rule in enumerate(normalized):
|
| 214 |
+
if all(abs(a - b) <= .01 for a, b in zip(rect, rule["rect"])):
|
| 215 |
+
original = _rgb(rule["old"])
|
| 216 |
+
if (fill is None or stroke is None
|
| 217 |
+
or any(abs(a - b) > tolerance for a, b in zip(fill, original))
|
| 218 |
+
or any(abs(a - b) > tolerance for a, b in zip(stroke, original))):
|
| 219 |
+
raise ValueError("Scoped rectangle fill/stroke differs from the required original colour")
|
| 220 |
+
if index in matches:
|
| 221 |
+
raise ValueError("Overlapping scoped rectangle rules")
|
| 222 |
+
seen[rule_index] += 1
|
| 223 |
+
matches[index] = {**rule, "matched_rect": rect, "rule_index": rule_index,
|
| 224 |
+
"original_paint_operator": op, "fill_before": fill,
|
| 225 |
+
"stroke_before": stroke}
|
| 226 |
+
points, invalid_path = [], False
|
| 227 |
+
if stack or any(seen[index] != 1 for index in range(len(normalized))):
|
| 228 |
+
raise ValueError("Every scoped rectangle must match exactly one filled-and-stroked patch")
|
| 229 |
+
return matches
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def recolor_pdf(source: Path, destination: Path, mapping: dict[str, str], *,
|
| 233 |
+
rectangle_rules: list[dict] | None = None, rgb_tolerance: float = RGB_TOLERANCE) -> dict:
|
| 234 |
+
"""Write a new PDF, changing only mapped ``rg``/``RG`` operands.
|
| 235 |
+
|
| 236 |
+
An existing destination, zero mapped hits for a nonempty mapping, or any
|
| 237 |
+
preservation failure raises. Originals are never overwritten. Matches are
|
| 238 |
+
simultaneous, so a new colour is not subsequently remapped within a chain.
|
| 239 |
+
"""
|
| 240 |
+
source, destination = Path(source).resolve(), Path(destination).resolve()
|
| 241 |
+
if source == destination or destination.exists():
|
| 242 |
+
raise ValueError("Palette variants require a new destination distinct from the source")
|
| 243 |
+
normalized = {_hex(old): _hex(new) for old, new in mapping.items()}
|
| 244 |
+
if len(normalized) != len(mapping):
|
| 245 |
+
raise ValueError("Duplicate normalized source colours")
|
| 246 |
+
rgb_map = [(old, new, _rgb(old), _rgb(new)) for old, new in normalized.items()]
|
| 247 |
+
if not math.isfinite(rgb_tolerance) or not 0 < rgb_tolerance < 1e-4:
|
| 248 |
+
raise ValueError("RGB tolerance must be positive and far below one 8-bit colour step")
|
| 249 |
+
rectangle_rules = rectangle_rules or []
|
| 250 |
+
before_source_sha = _file_sha(source)
|
| 251 |
+
before_geometry = _geometry(source)
|
| 252 |
+
changes = []
|
| 253 |
+
counts = Counter()
|
| 254 |
+
rectangle_proof = []
|
| 255 |
+
inserted_by_stream = {}
|
| 256 |
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
| 257 |
+
temporary = None
|
| 258 |
+
try:
|
| 259 |
+
with pikepdf.open(source) as pdf:
|
| 260 |
+
before_images = _image_payloads(pdf)
|
| 261 |
+
streams = _content_streams(pdf)
|
| 262 |
+
if rectangle_rules and (len(pdf.pages) != 1
|
| 263 |
+
or getattr(pdf.pages[0].obj.Contents, "_type_name", "") != "stream"):
|
| 264 |
+
raise ValueError("Scoped rectangles require one page with one content stream")
|
| 265 |
+
fingerprints = []
|
| 266 |
+
for label, stream in streams:
|
| 267 |
+
instructions = list(pikepdf.parse_content_stream(stream))
|
| 268 |
+
scoped = (_rectangle_matches(pdf, instructions, rectangle_rules, rgb_tolerance)
|
| 269 |
+
if rectangle_rules and label == "page0/Contents0" else {})
|
| 270 |
+
before_noncolor = _fingerprint(instructions, ignore_rgb=True)
|
| 271 |
+
fingerprints.append((label, before_noncolor))
|
| 272 |
+
rewritten = []
|
| 273 |
+
inserted = set()
|
| 274 |
+
stream_counts = Counter()
|
| 275 |
+
for index, instruction in enumerate(instructions):
|
| 276 |
+
op, operands = str(instruction.operator), instruction.operands
|
| 277 |
+
replacement = None
|
| 278 |
+
if op in {"rg", "RG"} and len(operands) == 3:
|
| 279 |
+
numbers = tuple(float(value) for value in operands)
|
| 280 |
+
for old, new, original_rgb, target_rgb in rgb_map:
|
| 281 |
+
if all(abs(a - b) <= rgb_tolerance for a, b in zip(numbers, original_rgb)):
|
| 282 |
+
counts[(old, new, op)] += 1
|
| 283 |
+
if old != new:
|
| 284 |
+
replacement = [Decimal(f"{value:.10f}") for value in target_rgb]
|
| 285 |
+
stream_counts[(old, new, op)] += 1
|
| 286 |
+
break
|
| 287 |
+
if index in scoped:
|
| 288 |
+
rule = scoped[index]
|
| 289 |
+
values = [Decimal(f"{value:.10f}") for value in _rgb(rule["new"])]
|
| 290 |
+
for operator, operands in [("q", []), ("rg", values), ("RG", values)]:
|
| 291 |
+
inserted.add(len(rewritten))
|
| 292 |
+
rewritten.append(pikepdf.ContentStreamInstruction(operands, pikepdf.Operator(operator)))
|
| 293 |
+
rewritten.append(instruction)
|
| 294 |
+
inserted.add(len(rewritten))
|
| 295 |
+
rewritten.append(pikepdf.ContentStreamInstruction([], pikepdf.Operator("Q")))
|
| 296 |
+
rectangle_proof.append({"stream": label, **rule})
|
| 297 |
+
stream_counts[(rule["old"], rule["new"], "scoped_rectangle")] += 1
|
| 298 |
+
else:
|
| 299 |
+
rewritten.append(pikepdf.ContentStreamInstruction(replacement, instruction.operator)
|
| 300 |
+
if replacement is not None else instruction)
|
| 301 |
+
if stream_counts:
|
| 302 |
+
encoded = pikepdf.unparse_content_stream(rewritten)
|
| 303 |
+
stream.write(encoded)
|
| 304 |
+
reparsed = list(pikepdf.parse_content_stream(stream))
|
| 305 |
+
projected = [instruction for index, instruction in enumerate(reparsed) if index not in inserted]
|
| 306 |
+
after_noncolor = _fingerprint(projected, ignore_rgb=True)
|
| 307 |
+
if before_noncolor != after_noncolor:
|
| 308 |
+
raise ValueError(f"Non-colour instructions changed in {label}")
|
| 309 |
+
if _fingerprint(rewritten, ignore_rgb=False) != _fingerprint(reparsed, ignore_rgb=False):
|
| 310 |
+
raise ValueError(f"Unexpected instruction serialization change in {label}")
|
| 311 |
+
changes.append({"stream": label, "noncolor_operator_sha256_before": before_noncolor,
|
| 312 |
+
"noncolor_operator_sha256_after": after_noncolor,
|
| 313 |
+
"colour_operators_changed": sum(stream_counts.values())})
|
| 314 |
+
inserted_by_stream[label] = inserted
|
| 315 |
+
if normalized and not counts:
|
| 316 |
+
raise ValueError("No explicit RGB operators matched the supplied mapping")
|
| 317 |
+
with tempfile.NamedTemporaryFile(dir=destination.parent, prefix=".palette-", suffix=".pdf", delete=False) as handle:
|
| 318 |
+
temporary = Path(handle.name)
|
| 319 |
+
pdf.save(temporary)
|
| 320 |
+
# Verify the serialized document, not only its in-memory representation.
|
| 321 |
+
with pikepdf.open(temporary) as saved:
|
| 322 |
+
after_images = _image_payloads(saved)
|
| 323 |
+
after_streams = []
|
| 324 |
+
for label, stream in _content_streams(saved):
|
| 325 |
+
instructions = list(pikepdf.parse_content_stream(stream))
|
| 326 |
+
projected = [instruction for index, instruction in enumerate(instructions)
|
| 327 |
+
if index not in inserted_by_stream.get(label, set())]
|
| 328 |
+
after_streams.append((label, _fingerprint(projected, ignore_rgb=True)))
|
| 329 |
+
if fingerprints != after_streams:
|
| 330 |
+
raise ValueError("Serialized PDF changed the non-colour instruction/resource traversal")
|
| 331 |
+
if before_images != after_images:
|
| 332 |
+
raise ValueError("Raster image payload or colour-space metadata changed")
|
| 333 |
+
if before_geometry != _geometry(temporary):
|
| 334 |
+
raise ValueError("Text geometry or page rectangles changed")
|
| 335 |
+
if before_source_sha != _file_sha(source):
|
| 336 |
+
raise ValueError("Source changed during palette conversion")
|
| 337 |
+
# No overwrite window if another caller creates the same destination.
|
| 338 |
+
os.link(temporary, destination)
|
| 339 |
+
proof = {
|
| 340 |
+
"schema": "pbisc.vector-method-palette.v1", "source": str(source),
|
| 341 |
+
"source_sha256": before_source_sha, "destination": str(destination),
|
| 342 |
+
"destination_sha256": _file_sha(destination), "mapping": normalized,
|
| 343 |
+
"rgb_absolute_tolerance": rgb_tolerance, "streams_inspected": len(fingerprints),
|
| 344 |
+
"modified_streams": len(changes), "stream_checks": changes,
|
| 345 |
+
"colour_counts": [{"old": old, "new": new, "operator": op, "count": count}
|
| 346 |
+
for (old, new, op), count in sorted(counts.items())],
|
| 347 |
+
"image_payload_count": len(before_images), "image_payloads": before_images,
|
| 348 |
+
"rectangle_rules_matched": len(rectangle_proof), "rectangle_checks": rectangle_proof,
|
| 349 |
+
"scope_insertions": "Only balanced q/RGB/RGB/paint/Q wrappers; original non-colour operators preserved",
|
| 350 |
+
"preservation": {"noncolor_operators": True, "text_geometry": True,
|
| 351 |
+
"page_rectangles": True, "image_payloads": True,
|
| 352 |
+
"source_unchanged": True}, "preservation_pass": True,
|
| 353 |
+
}
|
| 354 |
+
return proof
|
| 355 |
+
finally:
|
| 356 |
+
if temporary is not None:
|
| 357 |
+
temporary.unlink(missing_ok=True)
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def render_pdf_to_png(pdf: Path, png: Path, dpi: float = 200) -> dict:
|
| 361 |
+
"""Render a single-page vector PDF at its unchanged bounds; no pixel edits."""
|
| 362 |
+
pdf, png = Path(pdf).resolve(), Path(png).resolve()
|
| 363 |
+
if png.exists() or png == pdf:
|
| 364 |
+
raise ValueError("Rendering requires a new PNG destination")
|
| 365 |
+
if not math.isfinite(dpi) or dpi <= 0:
|
| 366 |
+
raise ValueError("dpi must be finite and positive")
|
| 367 |
+
with fitz.open(pdf) as document:
|
| 368 |
+
if len(document) != 1:
|
| 369 |
+
raise ValueError("Figure rendering requires exactly one PDF page")
|
| 370 |
+
page = document[0]
|
| 371 |
+
pixmap = page.get_pixmap(matrix=fitz.Matrix(dpi / 72, dpi / 72), alpha=False)
|
| 372 |
+
expected = (page.rect.width * dpi / 72, page.rect.height * dpi / 72)
|
| 373 |
+
if abs(pixmap.width - expected[0]) > 1 or abs(pixmap.height - expected[1]) > 1:
|
| 374 |
+
raise ValueError("Rendered image dimensions differ from PDF page bounds")
|
| 375 |
+
payload = pixmap.tobytes("png")
|
| 376 |
+
png.parent.mkdir(parents=True, exist_ok=True)
|
| 377 |
+
with png.open("xb") as handle:
|
| 378 |
+
handle.write(payload)
|
| 379 |
+
return {"pdf": str(pdf), "png": str(png), "dpi": dpi,
|
| 380 |
+
"page_rect": list(page.rect), "width": pixmap.width, "height": pixmap.height,
|
| 381 |
+
"png_sha256": hashlib.sha256(payload).hexdigest(),
|
| 382 |
+
"rendering": "native PDF rendering; no raster recolouring"}
|
paper-releases/pbisc-diffusion/updates/20261013T022035Z-pbisc-red-scsemi-blue/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/verify_review_palette.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Audit colour-only native-vector transformations and fixed numerical evidence."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import hashlib,json
|
| 4 |
+
import pikepdf
|
| 5 |
+
from review_palette_pdf import _content_streams
|
| 6 |
+
D=Path(__file__).resolve().parents[1];A=D/'data/method_palette_20261013'
|
| 7 |
+
def sha(p):
|
| 8 |
+
with Path(p).open('rb') as f:return hashlib.file_digest(f,'sha256').hexdigest()
|
| 9 |
+
old=json.loads((A/'numeric_sources_before.json').read_text())
|
| 10 |
+
for p,h in old.items():assert sha(p)==h,p
|
| 11 |
+
before=json.loads((A/'before_results_review_20261013_provenance.json').read_text())
|
| 12 |
+
now=json.loads((D/'data/results_review_20261013_provenance.json').read_text())
|
| 13 |
+
assert before['plot_calculations']==now['plot_calculations'],'numerical summaries changed'
|
| 14 |
+
prior=json.loads((A/'before_results_review_20261013_spec.json').read_text())['slides']
|
| 15 |
+
current=json.loads((D/'data/results_review_20261013_spec.json').read_text())['slides']
|
| 16 |
+
assert len(prior)==len(current)==34
|
| 17 |
+
for i,(a,b) in enumerate(zip(prior,current),1):
|
| 18 |
+
for field in ('title','section_label','footnote','keywords','items','rows'):
|
| 19 |
+
assert a.get(field)==b.get(field),(i,field)
|
| 20 |
+
policy=json.loads((A/'palette.json').read_text());catalog=json.loads((A/'ASSET_MAP.json').read_text())
|
| 21 |
+
proofs=[];preserved=[]
|
| 22 |
+
for rec in catalog['records']:
|
| 23 |
+
if rec['action']=='preserved':
|
| 24 |
+
preserved.append(rec['asset']);continue
|
| 25 |
+
p=D/rec['proof'];proof=json.loads(p.read_text())
|
| 26 |
+
assert proof['preservation_pass']
|
| 27 |
+
assert all(proof['preservation'].values()),p
|
| 28 |
+
assert sha(proof['source'])==proof['source_sha256'],p
|
| 29 |
+
assert sha(proof['destination'])==proof['destination_sha256'],p
|
| 30 |
+
assert sha(proof['original_png'])==proof['original_png_sha256'],p
|
| 31 |
+
assert sha(proof['render']['png'])==proof['render']['png_sha256'],p
|
| 32 |
+
remaining=[]
|
| 33 |
+
with pikepdf.open(proof['destination']) as pdf:
|
| 34 |
+
for name,stream in _content_streams(pdf):
|
| 35 |
+
for inst in pikepdf.parse_content_stream(stream):
|
| 36 |
+
if str(inst.operator) not in ('rg','RG'):continue
|
| 37 |
+
rgb=[float(x) for x in inst.operands]
|
| 38 |
+
for old_hex,new_hex in proof['mapping'].items():
|
| 39 |
+
if old_hex==new_hex:continue
|
| 40 |
+
expected=[int(old_hex[j:j+2],16)/255 for j in (1,3,5)]
|
| 41 |
+
if len(rgb)==3 and all(abs(x-y)<=proof['rgb_absolute_tolerance'] for x,y in zip(rgb,expected)):
|
| 42 |
+
remaining.append((name,str(inst.operator),old_hex))
|
| 43 |
+
assert not remaining,(p,remaining[:3])
|
| 44 |
+
if Path(proof['source']).stem=='sec05_cells_metrics':assert proof['rectangle_rules_matched']==4
|
| 45 |
+
proofs.append({'asset':rec['asset'],'proof':str(p),'colour_operators_changed':sum(x['count'] for x in proof['colour_counts']),
|
| 46 |
+
'rectangles_changed':proof.get('rectangle_rules_matched',0),'preservation_pass':True})
|
| 47 |
+
assert len(proofs)==25 and len(preserved)==7,(len(proofs),len(preserved))
|
| 48 |
+
report={'schema':'pbisc.method-palette-verification.v1','slides':34,'primary':policy['primary'],
|
| 49 |
+
'recolored_figures':len(proofs),'preserved_nonmethod_figures':len(preserved),
|
| 50 |
+
'numeric_csv_hashes_unchanged':len(old),'derived_numbers_unchanged':True,'slide_text_unchanged':True,
|
| 51 |
+
'all_vector_geometry_and_raster_payload_checks_pass':True,'no_old_mapped_method_colors_remain':True,
|
| 52 |
+
'checks':proofs,'preserved_assets':preserved}
|
| 53 |
+
(A/'VERIFICATION.json').write_text(json.dumps(report,indent=2)+'\n')
|
| 54 |
+
print(json.dumps({k:v for k,v in report.items() if k not in ('checks','preserved_assets')},indent=2))
|