tilesig 0.1.0.dev0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- tilesig/__init__.py +124 -0
- tilesig/_bundle_data.py +76 -0
- tilesig/_bundle_metadata.py +199 -0
- tilesig/_gpu_linkage_worker.py +147 -0
- tilesig/_version.py +2 -0
- tilesig/algorithm_adapters.py +130 -0
- tilesig/algorithm_binding.py +157 -0
- tilesig/algorithm_types.py +251 -0
- tilesig/algorithms.py +55 -0
- tilesig/annotation.py +1152 -0
- tilesig/annotation_layout.py +104 -0
- tilesig/annotation_names.py +174 -0
- tilesig/annotation_ops.py +199 -0
- tilesig/annotations_extra.py +1573 -0
- tilesig/api.py +861 -0
- tilesig/appearance.py +707 -0
- tilesig/axes.py +146 -0
- tilesig/barplot.py +337 -0
- tilesig/block_heatmap.py +158 -0
- tilesig/block_summary.py +231 -0
- tilesig/bundle_io.py +92 -0
- tilesig/cell_labels.py +68 -0
- tilesig/cell_mask.py +70 -0
- tilesig/clustering.py +39 -0
- tilesig/comparison.py +158 -0
- tilesig/compatibility.py +199 -0
- tilesig/compatibility_extra.py +111 -0
- tilesig/composition_controls.py +132 -0
- tilesig/composition_layout.py +121 -0
- tilesig/config.py +343 -0
- tilesig/decoration_context.py +53 -0
- tilesig/decoration_selection.py +56 -0
- tilesig/decorations.py +166 -0
- tilesig/dendrograms.py +299 -0
- tilesig/diagonal.py +213 -0
- tilesig/distribution_heatmaps.py +164 -0
- tilesig/dot_heatmap.py +274 -0
- tilesig/genomic.py +87 -0
- tilesig/gpu_bridge.py +214 -0
- tilesig/gpu_raster.py +128 -0
- tilesig/graphics.py +92 -0
- tilesig/grouped_textboxes.py +133 -0
- tilesig/h5ad.py +742 -0
- tilesig/h5ad_subset.py +245 -0
- tilesig/helpers.py +246 -0
- tilesig/interval_sets.py +120 -0
- tilesig/item_display_tree.py +81 -0
- tilesig/legend_ticks.py +60 -0
- tilesig/legends.py +607 -0
- tilesig/matplotlib_integration.py +50 -0
- tilesig/matrix_scaling.py +40 -0
- tilesig/matrix_source.py +180 -0
- tilesig/name_layout.py +93 -0
- tilesig/object_ops.py +505 -0
- tilesig/options.py +44 -0
- tilesig/ordering_policy.py +91 -0
- tilesig/palettes.py +101 -0
- tilesig/parent_dendrogram.py +199 -0
- tilesig/pdf_renderer.py +717 -0
- tilesig/png_renderer.py +559 -0
- tilesig/preparation_cache.py +94 -0
- tilesig/prepared.py +179 -0
- tilesig/r_cluster_controls.py +138 -0
- tilesig/r_layout_controls.py +92 -0
- tilesig/r_raster.py +235 -0
- tilesig/renderer.py +3611 -0
- tilesig/renderer_old.py +2060 -0
- tilesig/reproducibility.py +88 -0
- tilesig/sets.py +407 -0
- tilesig/signal_heatmap.py +453 -0
- tilesig/single_cell.py +251 -0
- tilesig/slice_drawing.py +100 -0
- tilesig/slice_geometry.py +48 -0
- tilesig/slice_summary.py +80 -0
- tilesig/source_render.py +252 -0
- tilesig/specialized.py +520 -0
- tilesig/specialized_support.py +172 -0
- tilesig/streaming_pdf.py +118 -0
- tilesig/streaming_svg.py +72 -0
- tilesig/style.py +148 -0
- tilesig/text_boxes.py +158 -0
- tilesig/text_layout.py +45 -0
- tilesig/text_styles.py +83 -0
- tilesig/titles.py +191 -0
- tilesig/tree_styles.py +45 -0
- tilesig/unicode_pdf.py +119 -0
- tilesig/upset_annotations.py +58 -0
- tilesig/vector_grid.py +13 -0
- tilesig/within_block_order.py +167 -0
- tilesig-0.1.0.dev0.dist-info/METADATA +107 -0
- tilesig-0.1.0.dev0.dist-info/RECORD +94 -0
- tilesig-0.1.0.dev0.dist-info/WHEEL +5 -0
- tilesig-0.1.0.dev0.dist-info/licenses/LICENSE +21 -0
- tilesig-0.1.0.dev0.dist-info/top_level.txt +1 -0
tilesig/pdf_renderer.py
ADDED
|
@@ -0,0 +1,717 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Native, fast PDF writer for ClusterMapPlotter.
|
|
3
|
+
|
|
4
|
+
Instead of building a huge SVG string and re-parsing it with svglib (which is
|
|
5
|
+
slow for large heatmaps), the `PdfSink` class consumes the exact same SVG
|
|
6
|
+
fragments the renderer already emits through ``f.write(...)`` and translates
|
|
7
|
+
them into PDF primitives directly. The heatmap blocks are handed over as raw
|
|
8
|
+
PNG bytes via :meth:`PdfSink.write_image` (no base64 round-trip) and embedded
|
|
9
|
+
as PDF image XObjects; the colourbar, annotations, dendrograms and text stay
|
|
10
|
+
vector. No reportlab/PIL image decoding is needed, so the PDF path runs at
|
|
11
|
+
about the same speed as the SVG path.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import base64
|
|
15
|
+
import html
|
|
16
|
+
import math
|
|
17
|
+
import re
|
|
18
|
+
import zlib
|
|
19
|
+
|
|
20
|
+
import cv2
|
|
21
|
+
import numpy as np
|
|
22
|
+
|
|
23
|
+
_ELEMENT_RE = re.compile(
|
|
24
|
+
r'<(?P<close>/?)(?P<tag>[a-zA-Z][\w-]*)(?P<attrs>[^>]*?)(?P<end>/?)>'
|
|
25
|
+
)
|
|
26
|
+
_ATTR_RE = re.compile(r'([\w:.-]+)\s*=\s*("[^"]*"|\'[^\']*\')')
|
|
27
|
+
_NUMBER = r'([-+]?(?:\d*\.?\d+)(?:[eE][-+]?\d+)?)'
|
|
28
|
+
_TRANSLATE_RE = re.compile(r'translate\(\s*'+_NUMBER+r'[\s,]+'+_NUMBER+r'\s*\)')
|
|
29
|
+
_ROTATE_RE = re.compile(r'rotate\(\s*'+_NUMBER+r'[\s,]+'+_NUMBER+r'[\s,]+'+_NUMBER+r'\s*\)')
|
|
30
|
+
_IMG_ATTRS_RE = re.compile(r'(?<![-\w])(x|y|width|height)\s*=\s*["\']?(-?[\d.]+)')
|
|
31
|
+
|
|
32
|
+
_FONT_OBJ = {
|
|
33
|
+
'Helvetica': '/Helvetica',
|
|
34
|
+
'Helvetica-Bold': '/Helvetica-Bold',
|
|
35
|
+
'Helvetica-Oblique': '/Helvetica-Oblique',
|
|
36
|
+
'Helvetica-BoldOblique': '/Helvetica-BoldOblique',
|
|
37
|
+
'Courier': '/Courier',
|
|
38
|
+
'Courier-Bold': '/Courier-Bold',
|
|
39
|
+
'Courier-Oblique': '/Courier-Oblique',
|
|
40
|
+
'Courier-BoldOblique': '/Courier-BoldOblique',
|
|
41
|
+
'Times-Roman': '/Times-Roman',
|
|
42
|
+
'Times-Bold': '/Times-Bold',
|
|
43
|
+
'Times-Italic': '/Times-Italic',
|
|
44
|
+
'Times-BoldItalic': '/Times-BoldItalic',
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
_text_width_cache = {}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _f(x):
|
|
51
|
+
"""Compact float -> PDF number bytes (no locale/exponent surprises)."""
|
|
52
|
+
s = '%g' % x
|
|
53
|
+
if 'e' in s or 'E' in s:
|
|
54
|
+
s = '%.3f' % x
|
|
55
|
+
return s.encode('ascii')
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _rgb(c):
|
|
59
|
+
return _f(c[0]) + b' ' + _f(c[1]) + b' ' + _f(c[2])
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _pdf_escape(s):
|
|
63
|
+
"""Wrap a string in PDF literal parens, escaping special chars."""
|
|
64
|
+
if not s:
|
|
65
|
+
return b'()'
|
|
66
|
+
s = str(s).encode('latin-1', 'replace').decode('latin-1')
|
|
67
|
+
s = s.replace('\\', '\\\\').replace('(', '\\(').replace(')', '\\)')
|
|
68
|
+
return ('(' + s + ')').encode('latin-1')
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _text_width(content, fname, size):
|
|
72
|
+
"""Approximate/measured text width in points for anchor adjustments."""
|
|
73
|
+
key = (content, fname, size)
|
|
74
|
+
w = _text_width_cache.get(key)
|
|
75
|
+
if w is not None:
|
|
76
|
+
return w
|
|
77
|
+
try:
|
|
78
|
+
from reportlab.pdfbase.pdfmetrics import stringWidth
|
|
79
|
+
w = stringWidth(content, fname, size)
|
|
80
|
+
except Exception:
|
|
81
|
+
w = len(content) * size * 0.5
|
|
82
|
+
_text_width_cache[key] = w
|
|
83
|
+
return w
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class _IndexedImage:
|
|
87
|
+
"""A palette (indexed-colour) image payload for a PDF XObject."""
|
|
88
|
+
|
|
89
|
+
__slots__ = ('indices', 'palette_hex', 'width', 'height')
|
|
90
|
+
|
|
91
|
+
def __init__(self, indices, palette_hex, width, height):
|
|
92
|
+
self.indices = indices
|
|
93
|
+
self.palette_hex = palette_hex
|
|
94
|
+
self.width = width
|
|
95
|
+
self.height = height
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class _FontName(str):
|
|
99
|
+
"""Legacy font-name string with optional native family metadata."""
|
|
100
|
+
def __new__(cls,name,family=None):
|
|
101
|
+
value=super().__new__(cls,name);value.family=family;return value
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class PdfSink:
|
|
105
|
+
"""Receives SVG fragments (via ``.write``) and buffers drawing ops for a PDF.
|
|
106
|
+
|
|
107
|
+
The object can be passed to any renderer method that expects an ``f``
|
|
108
|
+
file-like sink (e.g. ``_write_heatmap_blocks``, ``_draw_annotations``).
|
|
109
|
+
Call :meth:`finalize` once all elements have been written to produce the
|
|
110
|
+
actual PDF file.
|
|
111
|
+
"""
|
|
112
|
+
|
|
113
|
+
_NAMED = {
|
|
114
|
+
'white': (1, 1, 1),
|
|
115
|
+
'black': (0, 0, 0),
|
|
116
|
+
'red': (1, 0, 0),
|
|
117
|
+
'gray': (0.5, 0.5, 0.5),
|
|
118
|
+
'grey': (0.5, 0.5, 0.5),
|
|
119
|
+
'blue': (0, 0, 1),
|
|
120
|
+
'green': (0, 1, 0),
|
|
121
|
+
'orange': (1, 0.65, 0),
|
|
122
|
+
'yellow': (1, 1, 0),
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
def __init__(self, page_w=0, page_h=0):
|
|
126
|
+
self._ops = []
|
|
127
|
+
self._gattrs = {
|
|
128
|
+
'fill': 'black',
|
|
129
|
+
'stroke': None,
|
|
130
|
+
'stroke-width': None,
|
|
131
|
+
'font-size': None,
|
|
132
|
+
'font-family': None,
|
|
133
|
+
'font-weight': None,
|
|
134
|
+
'font-style': None,
|
|
135
|
+
'text-anchor': None,
|
|
136
|
+
'dominant-baseline': None,
|
|
137
|
+
}
|
|
138
|
+
self._gstack = []
|
|
139
|
+
self._tx = 0
|
|
140
|
+
self._ty = 0
|
|
141
|
+
self._tstack = []
|
|
142
|
+
self._pending_text = None
|
|
143
|
+
self._page_w = float(page_w)
|
|
144
|
+
self._page_h = float(page_h)
|
|
145
|
+
|
|
146
|
+
# ── helpers ─────────────────────────────────────────────────────────
|
|
147
|
+
|
|
148
|
+
@staticmethod
|
|
149
|
+
def _parse_attrs(attr_text):
|
|
150
|
+
d = {}
|
|
151
|
+
for m in _ATTR_RE.finditer(attr_text):
|
|
152
|
+
key = m.group(1)
|
|
153
|
+
val = m.group(2)
|
|
154
|
+
if len(val) >= 2 and val[0] in ('"', "'") and val[-1] == val[0]:
|
|
155
|
+
val = val[1:-1]
|
|
156
|
+
d[key] = val
|
|
157
|
+
return d
|
|
158
|
+
|
|
159
|
+
@staticmethod
|
|
160
|
+
def _color(s):
|
|
161
|
+
if s is None:
|
|
162
|
+
return None
|
|
163
|
+
s = str(s).strip().lower()
|
|
164
|
+
if s in ('none', 'transparent', ''):
|
|
165
|
+
return None
|
|
166
|
+
if s in PdfSink._NAMED:
|
|
167
|
+
return PdfSink._NAMED[s]
|
|
168
|
+
if s.startswith('#'):
|
|
169
|
+
if len(s) == 7:
|
|
170
|
+
try:
|
|
171
|
+
return tuple(int(s[i:i + 2], 16) / 255.0 for i in (1, 3, 5))
|
|
172
|
+
except ValueError:
|
|
173
|
+
return None
|
|
174
|
+
if len(s) == 4:
|
|
175
|
+
try:
|
|
176
|
+
return tuple(int(c * 2, 16) / 255.0 for c in s[1:])
|
|
177
|
+
except ValueError:
|
|
178
|
+
return None
|
|
179
|
+
return None
|
|
180
|
+
m = re.match(r'rgb\(\s*([^)]+)\s*\)', s)
|
|
181
|
+
if m:
|
|
182
|
+
out = []
|
|
183
|
+
for p in m.group(1).split(','):
|
|
184
|
+
p = p.strip()
|
|
185
|
+
try:
|
|
186
|
+
if p.endswith('%'):
|
|
187
|
+
out.append(float(p[:-1]) / 100.0)
|
|
188
|
+
else:
|
|
189
|
+
v = float(p)
|
|
190
|
+
out.append(v / 255.0 if v > 1 else v)
|
|
191
|
+
except ValueError:
|
|
192
|
+
out.append(0.0)
|
|
193
|
+
if len(out) == 3:
|
|
194
|
+
return (out[0], out[1], out[2])
|
|
195
|
+
# Native callback fragments can use any SVG/CSS named color. The small
|
|
196
|
+
# hot-path table above stays intact; resolve other standard names only
|
|
197
|
+
# here so PNG and PDF do not silently drop a valid SVG fill/stroke.
|
|
198
|
+
from matplotlib.colors import CSS4_COLORS
|
|
199
|
+
value = CSS4_COLORS.get(s)
|
|
200
|
+
if value is not None:
|
|
201
|
+
return tuple(int(value[i:i + 2], 16) / 255.0 for i in (1, 3, 5))
|
|
202
|
+
return None
|
|
203
|
+
|
|
204
|
+
def _get(self, key):
|
|
205
|
+
return self._gattrs.get(key)
|
|
206
|
+
|
|
207
|
+
def _fill_attr(self, attrs, key):
|
|
208
|
+
if attrs.get(key) is not None:
|
|
209
|
+
return attrs[key]
|
|
210
|
+
return self._get(key)
|
|
211
|
+
|
|
212
|
+
def _push_attrs(self, attrs):
|
|
213
|
+
self._gstack.append(dict(self._gattrs))
|
|
214
|
+
for k, v in attrs.items():
|
|
215
|
+
if k in self._gattrs:
|
|
216
|
+
self._gattrs[k] = v
|
|
217
|
+
self._tstack.append((self._tx, self._ty))
|
|
218
|
+
tr = attrs.get('transform')
|
|
219
|
+
if tr:
|
|
220
|
+
m = _TRANSLATE_RE.match(tr)
|
|
221
|
+
if m:
|
|
222
|
+
self._tx += float(m.group(1))
|
|
223
|
+
self._ty += float(m.group(2))
|
|
224
|
+
|
|
225
|
+
def _pop_attrs(self):
|
|
226
|
+
if self._gstack:
|
|
227
|
+
self._gattrs = self._gstack.pop()
|
|
228
|
+
if self._tstack:
|
|
229
|
+
self._tx, self._ty = self._tstack.pop()
|
|
230
|
+
|
|
231
|
+
def _stroke_width(self, attrs):
|
|
232
|
+
sw = self._fill_attr(attrs, 'stroke-width')
|
|
233
|
+
if sw is None:
|
|
234
|
+
return 1.0
|
|
235
|
+
try:
|
|
236
|
+
return float(sw)
|
|
237
|
+
except (TypeError, ValueError):
|
|
238
|
+
return 1.0
|
|
239
|
+
|
|
240
|
+
def _stroke_color(self,attrs):
|
|
241
|
+
# SVG width zero means invisible, while PDF width zero is a hairline.
|
|
242
|
+
return self._color(self._fill_attr(attrs,'stroke')) if self._stroke_width(attrs)>0 else None
|
|
243
|
+
|
|
244
|
+
def _font_name(self, attrs):
|
|
245
|
+
family = self._fill_attr(attrs, 'font-family') or 'Arial'
|
|
246
|
+
low = family.lower()
|
|
247
|
+
if 'mono' in low or 'courier' in low:
|
|
248
|
+
fname = 'Courier'
|
|
249
|
+
elif 'times' in low or 'serif' in low:
|
|
250
|
+
fname = 'Times-Roman'
|
|
251
|
+
else:
|
|
252
|
+
fname = 'Helvetica'
|
|
253
|
+
weight = str(self._fill_attr(attrs, 'font-weight') or '').lower()
|
|
254
|
+
if weight in ('bold', '700'):
|
|
255
|
+
fname = {
|
|
256
|
+
'Helvetica': 'Helvetica-Bold',
|
|
257
|
+
'Courier': 'Courier-Bold',
|
|
258
|
+
'Times-Roman': 'Times-Bold',
|
|
259
|
+
}[fname]
|
|
260
|
+
if str(self._fill_attr(attrs,'font-style') or '').lower() in ('italic','oblique'):
|
|
261
|
+
fname={'Helvetica':'Helvetica-Oblique','Helvetica-Bold':'Helvetica-BoldOblique','Courier':'Courier-Oblique','Courier-Bold':'Courier-BoldOblique','Times-Roman':'Times-Italic','Times-Bold':'Times-BoldItalic'}[fname]
|
|
262
|
+
return fname
|
|
263
|
+
|
|
264
|
+
def _append_op(self, op):
|
|
265
|
+
self._ops.append(op)
|
|
266
|
+
|
|
267
|
+
# ── element emitters ────────────────────────────────────────────────
|
|
268
|
+
|
|
269
|
+
def _emit_rect(self, attrs):
|
|
270
|
+
x = float(attrs.get('x', 0)) + self._tx
|
|
271
|
+
y = float(attrs.get('y', 0)) + self._ty
|
|
272
|
+
w = attrs.get('width', '0')
|
|
273
|
+
h = attrs.get('height', '0')
|
|
274
|
+
if str(w).strip() == '100%':
|
|
275
|
+
w = self._page_w
|
|
276
|
+
if str(h).strip() == '100%':
|
|
277
|
+
h = self._page_h
|
|
278
|
+
w = float(w)
|
|
279
|
+
h = float(h)
|
|
280
|
+
fill = self._color(self._fill_attr(attrs, 'fill'))
|
|
281
|
+
stroke = self._stroke_color(attrs)
|
|
282
|
+
sw = self._stroke_width(attrs)
|
|
283
|
+
fa = None
|
|
284
|
+
if attrs.get('fill-opacity') is not None:
|
|
285
|
+
try:
|
|
286
|
+
fa = float(attrs['fill-opacity'])
|
|
287
|
+
except (TypeError, ValueError):
|
|
288
|
+
fa = None
|
|
289
|
+
self._append_op(('rect', x, y, w, h, fill, stroke, sw, fa))
|
|
290
|
+
|
|
291
|
+
def _emit_line(self, attrs):
|
|
292
|
+
x1 = float(attrs.get('x1', 0)) + self._tx
|
|
293
|
+
y1 = float(attrs.get('y1', 0)) + self._ty
|
|
294
|
+
x2 = float(attrs.get('x2', 0)) + self._tx
|
|
295
|
+
y2 = float(attrs.get('y2', 0)) + self._ty
|
|
296
|
+
stroke = self._stroke_color(attrs)
|
|
297
|
+
sw = self._stroke_width(attrs)
|
|
298
|
+
if stroke is not None:
|
|
299
|
+
self._append_op(('line', x1, y1, x2, y2, stroke, sw))
|
|
300
|
+
|
|
301
|
+
def _emit_polyline(self, attrs):
|
|
302
|
+
pts = attrs.get('points', '')
|
|
303
|
+
coords = []
|
|
304
|
+
for pair in pts.split():
|
|
305
|
+
try:
|
|
306
|
+
px, py = pair.split(',')
|
|
307
|
+
coords.append((float(px) + self._tx, float(py) + self._ty))
|
|
308
|
+
except (ValueError, TypeError):
|
|
309
|
+
continue
|
|
310
|
+
if len(coords) < 2:
|
|
311
|
+
return
|
|
312
|
+
stroke = self._stroke_color(attrs)
|
|
313
|
+
sw = self._stroke_width(attrs)
|
|
314
|
+
if stroke is not None:
|
|
315
|
+
segs = []
|
|
316
|
+
for i in range(len(coords) - 1):
|
|
317
|
+
x0, y0 = coords[i]
|
|
318
|
+
x1, y1 = coords[i + 1]
|
|
319
|
+
segs.append((x0, y0, x1, y1))
|
|
320
|
+
self._append_op(('lines', segs, stroke, sw))
|
|
321
|
+
|
|
322
|
+
def _emit_circle(self, attrs):
|
|
323
|
+
cx = float(attrs.get('cx', 0)) + self._tx
|
|
324
|
+
cy = float(attrs.get('cy', 0)) + self._ty
|
|
325
|
+
r = float(attrs.get('r', 0))
|
|
326
|
+
fill = self._color(self._fill_attr(attrs, 'fill'))
|
|
327
|
+
stroke=self._stroke_color(attrs)
|
|
328
|
+
sw=self._stroke_width(attrs)
|
|
329
|
+
if r>0 and (fill is not None or stroke is not None):
|
|
330
|
+
self._append_op(('circle', cx, cy, r, fill, stroke, sw))
|
|
331
|
+
|
|
332
|
+
def _emit_image_fast(self, fragment):
|
|
333
|
+
"""Fast path for a single ``<image .../>`` fragment with a big base64 data URI.
|
|
334
|
+
|
|
335
|
+
The general regex parser is O(fragment-size) per element because the
|
|
336
|
+
non-greedy attribute scan probes the whole base64 payload. Rasterised
|
|
337
|
+
heatmaps emit many MB-sized image fragments, so we parse those with
|
|
338
|
+
dedicated linear helpers instead. The base64 payload is decoded to raw
|
|
339
|
+
PNG bytes (embedded into the PDF at :meth:`finalize`).
|
|
340
|
+
"""
|
|
341
|
+
gt = fragment.find('>')
|
|
342
|
+
body = fragment[:gt] if gt >= 0 else fragment
|
|
343
|
+
vals = {}
|
|
344
|
+
for m in _IMG_ATTRS_RE.finditer(body):
|
|
345
|
+
vals[m.group(1)] = float(m.group(2))
|
|
346
|
+
x = vals.get('x', 0.0) + self._tx
|
|
347
|
+
y = vals.get('y', 0.0) + self._ty
|
|
348
|
+
w = vals.get('width', 0.0)
|
|
349
|
+
h = vals.get('height', 0.0)
|
|
350
|
+
i = body.find('base64,')
|
|
351
|
+
if i < 0:
|
|
352
|
+
return
|
|
353
|
+
start = i + len('base64,')
|
|
354
|
+
end = body.find('"', start)
|
|
355
|
+
if end < 0:
|
|
356
|
+
end = len(body)
|
|
357
|
+
try:
|
|
358
|
+
png = base64.b64decode(body[start:end])
|
|
359
|
+
except Exception:
|
|
360
|
+
return
|
|
361
|
+
if not png:
|
|
362
|
+
return
|
|
363
|
+
self._append_op(('image', x, y, w, h, png))
|
|
364
|
+
|
|
365
|
+
def _emit_image(self, attrs):
|
|
366
|
+
x = float(attrs.get('x', 0)) + self._tx
|
|
367
|
+
y = float(attrs.get('y', 0)) + self._ty
|
|
368
|
+
w = float(attrs.get('width', 0))
|
|
369
|
+
h = float(attrs.get('height', 0))
|
|
370
|
+
href = attrs.get('xlink:href') or attrs.get('href')
|
|
371
|
+
if not href or not href.startswith('data:image/'):
|
|
372
|
+
return
|
|
373
|
+
try:
|
|
374
|
+
png = base64.b64decode(href.split(',', 1)[1])
|
|
375
|
+
except Exception:
|
|
376
|
+
return
|
|
377
|
+
if not png:
|
|
378
|
+
return
|
|
379
|
+
self._append_op(('image', x, y, w, h, png))
|
|
380
|
+
|
|
381
|
+
def _emit_text(self, attrs, content):
|
|
382
|
+
x = float(attrs.get('x', 0)) + self._tx
|
|
383
|
+
y = float(attrs.get('y', 0)) + self._ty
|
|
384
|
+
size = self._fill_attr(attrs, 'font-size')
|
|
385
|
+
try:
|
|
386
|
+
size = float(size) if size is not None else 12.0
|
|
387
|
+
except (TypeError, ValueError):
|
|
388
|
+
size = 12.0
|
|
389
|
+
fname = self._font_name(attrs)
|
|
390
|
+
# Only explicit text families override the sink's common family.
|
|
391
|
+
if attrs.get('font-family'):
|
|
392
|
+
fname = _FontName(fname,html.unescape(attrs['font-family']))
|
|
393
|
+
rgb = self._color(self._fill_attr(attrs, 'fill'))
|
|
394
|
+
anchor = self._fill_attr(attrs, 'text-anchor') or 'start'
|
|
395
|
+
dbl = self._fill_attr(attrs, 'dominant-baseline')
|
|
396
|
+
rot = None
|
|
397
|
+
tr = attrs.get('transform')
|
|
398
|
+
if tr:
|
|
399
|
+
m = _ROTATE_RE.match(tr)
|
|
400
|
+
if m:
|
|
401
|
+
rot = (float(m.group(1)), float(m.group(2))+self._tx, float(m.group(3))+self._ty)
|
|
402
|
+
content = html.unescape(content) if content else ''
|
|
403
|
+
self._append_op(('text', x, y, content, fname, size, rgb, anchor, dbl, rot))
|
|
404
|
+
|
|
405
|
+
# ── public API ──────────────────────────────────────────────────────
|
|
406
|
+
|
|
407
|
+
def write_image(self, x, y, w, h, png_bytes):
|
|
408
|
+
"""Direct image write used by the rasterised heatmap path (no base64)."""
|
|
409
|
+
if not png_bytes:
|
|
410
|
+
return
|
|
411
|
+
self._append_op(('image', float(x)+self._tx, float(y)+self._ty, float(w), float(h), bytes(png_bytes)))
|
|
412
|
+
|
|
413
|
+
def write_indexed_raster(self, x, y, w, h, indices, palette_rgb):
|
|
414
|
+
"""Embed a uint8 index array as a PDF ``/Indexed`` image.
|
|
415
|
+
|
|
416
|
+
Uses one byte per pixel instead of three and stores the palette once,
|
|
417
|
+
so the heatmap compresses roughly 3x faster and yields a smaller PDF.
|
|
418
|
+
"""
|
|
419
|
+
if indices is None:
|
|
420
|
+
return
|
|
421
|
+
arr = np.ascontiguousarray(indices, dtype=np.uint8)
|
|
422
|
+
ah, aw = arr.shape[:2]
|
|
423
|
+
pal = np.ascontiguousarray(palette_rgb, dtype=np.uint8).reshape(-1, 3)
|
|
424
|
+
if pal.shape[0] < 256:
|
|
425
|
+
pal = np.vstack([pal, np.zeros((256 - pal.shape[0], 3), np.uint8)])
|
|
426
|
+
palette_hex = pal[:256].tobytes().hex().encode('ascii')
|
|
427
|
+
self._append_op(('image', float(x)+self._tx, float(y)+self._ty, float(w), float(h),
|
|
428
|
+
_IndexedImage(arr.tobytes(), palette_hex, aw, ah)))
|
|
429
|
+
|
|
430
|
+
def write(self, fragment):
|
|
431
|
+
if not fragment:
|
|
432
|
+
return
|
|
433
|
+
stripped = fragment.lstrip()
|
|
434
|
+
if stripped.startswith('<image'):
|
|
435
|
+
self._emit_image_fast(fragment)
|
|
436
|
+
return
|
|
437
|
+
text_parts = []
|
|
438
|
+
last_end = 0
|
|
439
|
+
for m in _ELEMENT_RE.finditer(fragment):
|
|
440
|
+
gap = fragment[last_end:m.start()]
|
|
441
|
+
last_end = m.end()
|
|
442
|
+
is_close = m.group('close') == '/'
|
|
443
|
+
tag = m.group('tag')
|
|
444
|
+
attrs = self._parse_attrs(m.group('attrs'))
|
|
445
|
+
|
|
446
|
+
if self._pending_text is not None:
|
|
447
|
+
text_parts.append(gap)
|
|
448
|
+
|
|
449
|
+
if is_close:
|
|
450
|
+
if self._pending_text is not None and tag == 'text':
|
|
451
|
+
self._emit_text(self._pending_text, ''.join(text_parts))
|
|
452
|
+
self._pending_text = None
|
|
453
|
+
text_parts = []
|
|
454
|
+
elif tag == 'g':
|
|
455
|
+
self._pop_attrs()
|
|
456
|
+
continue
|
|
457
|
+
|
|
458
|
+
if tag == 'text':
|
|
459
|
+
self._pending_text = attrs
|
|
460
|
+
text_parts = []
|
|
461
|
+
elif tag == 'g':
|
|
462
|
+
self._push_attrs(attrs)
|
|
463
|
+
elif tag == 'svg':
|
|
464
|
+
try:
|
|
465
|
+
self._page_w = float(attrs.get('width', self._page_w))
|
|
466
|
+
self._page_h = float(attrs.get('height', self._page_h))
|
|
467
|
+
except (TypeError, ValueError):
|
|
468
|
+
pass
|
|
469
|
+
elif tag == 'rect':
|
|
470
|
+
self._emit_rect(attrs)
|
|
471
|
+
elif tag == 'line':
|
|
472
|
+
self._emit_line(attrs)
|
|
473
|
+
elif tag == 'polyline':
|
|
474
|
+
self._emit_polyline(attrs)
|
|
475
|
+
elif tag == 'polygon':
|
|
476
|
+
coords=[]
|
|
477
|
+
for pair in attrs.get('points','').split():
|
|
478
|
+
px,py=map(float,pair.split(','))
|
|
479
|
+
coords.append((px+self._tx,py+self._ty))
|
|
480
|
+
if len(coords)>=3:
|
|
481
|
+
fill=self._color(self._fill_attr(attrs,'fill'))
|
|
482
|
+
stroke=self._stroke_color(attrs)
|
|
483
|
+
alpha=attrs.get('fill-opacity')
|
|
484
|
+
if fill is not None or stroke is not None:self._append_op(('polygon',coords,fill,stroke,self._stroke_width(attrs),None if alpha is None else float(alpha)))
|
|
485
|
+
elif tag == 'circle':
|
|
486
|
+
self._emit_circle(attrs)
|
|
487
|
+
elif tag == 'image':
|
|
488
|
+
self._emit_image(attrs)
|
|
489
|
+
|
|
490
|
+
# ── raw PDF writer ──────────────────────────────────────────────────
|
|
491
|
+
|
|
492
|
+
@staticmethod
|
|
493
|
+
def _png_to_rgb(png_bytes):
|
|
494
|
+
"""Decode PNG bytes to (rgb_bytes, width, height)."""
|
|
495
|
+
arr = cv2.imdecode(np.frombuffer(png_bytes, np.uint8), cv2.IMREAD_COLOR)
|
|
496
|
+
if arr is None:
|
|
497
|
+
return b'\x00\x00\x00', 1, 1
|
|
498
|
+
h, w = arr.shape[:2]
|
|
499
|
+
rgb = cv2.cvtColor(arr, cv2.COLOR_BGR2RGB)
|
|
500
|
+
return rgb.tobytes(), w, h
|
|
501
|
+
|
|
502
|
+
def finalize(self, output_path, full_w, full_h):
|
|
503
|
+
"""Create the PDF file at ``output_path`` sized ``full_w`` x ``full_h``."""
|
|
504
|
+
W = float(full_w)
|
|
505
|
+
H = float(full_h)
|
|
506
|
+
|
|
507
|
+
# ---- scan resources used by the ops ----
|
|
508
|
+
fonts = []
|
|
509
|
+
font_idx = {}
|
|
510
|
+
alphas = [1.0]
|
|
511
|
+
alpha_idx = {1.0: 0}
|
|
512
|
+
images = []
|
|
513
|
+
img_idx = {}
|
|
514
|
+
for op in self._ops:
|
|
515
|
+
if op[0] == 'text':
|
|
516
|
+
fn = op[4]
|
|
517
|
+
if fn not in font_idx:
|
|
518
|
+
font_idx[fn] = len(fonts)
|
|
519
|
+
fonts.append(fn)
|
|
520
|
+
elif op[0] == 'rect':
|
|
521
|
+
fa = op[8]
|
|
522
|
+
if fa is not None and fa not in alpha_idx:
|
|
523
|
+
alpha_idx[fa] = len(alphas)
|
|
524
|
+
alphas.append(fa)
|
|
525
|
+
elif op[0] == 'image':
|
|
526
|
+
img_idx[id(op)] = len(images)
|
|
527
|
+
images.append(op)
|
|
528
|
+
|
|
529
|
+
# ---- build content stream ----
|
|
530
|
+
buf = []
|
|
531
|
+
cur_alpha = 0
|
|
532
|
+
|
|
533
|
+
def set_alpha(i):
|
|
534
|
+
nonlocal cur_alpha
|
|
535
|
+
if i != cur_alpha:
|
|
536
|
+
buf.append(b'/GS%d gs\n' % i)
|
|
537
|
+
cur_alpha = i
|
|
538
|
+
|
|
539
|
+
for op in self._ops:
|
|
540
|
+
kind = op[0]
|
|
541
|
+
if kind == 'polygon':
|
|
542
|
+
_,points,fill,stroke,sw,alpha=op
|
|
543
|
+
if fill is not None:buf.append(_rgb(fill)+b' rg ')
|
|
544
|
+
if stroke is not None:buf.append(_rgb(stroke)+b' RG '+_f(sw)+b' w ')
|
|
545
|
+
buf.append(_f(points[0][0])+b' '+_f(H-points[0][1])+b' m ')
|
|
546
|
+
for px,py in points[1:]:buf.append(_f(px)+b' '+_f(H-py)+b' l ')
|
|
547
|
+
buf.append(b'h '+(b'B' if fill is not None and stroke is not None else b'f' if fill is not None else b'S')+b'\n')
|
|
548
|
+
continue
|
|
549
|
+
if kind == 'rect':
|
|
550
|
+
_, x, y, w, h, fill, stroke, sw, fa = op
|
|
551
|
+
yp = H - (y + h)
|
|
552
|
+
if fa is not None:
|
|
553
|
+
set_alpha(alpha_idx[fa])
|
|
554
|
+
do_fill = fill is not None
|
|
555
|
+
do_stroke = stroke is not None
|
|
556
|
+
if do_fill:
|
|
557
|
+
buf.append(_rgb(fill) + b' rg ')
|
|
558
|
+
if do_stroke:
|
|
559
|
+
buf.append(_rgb(stroke) + b' RG ')
|
|
560
|
+
buf.append(_f(sw) + b' w ')
|
|
561
|
+
buf.append(_f(x) + b' ' + _f(yp) + b' ' + _f(w) + b' ' + _f(h) + b' re ')
|
|
562
|
+
if do_fill and do_stroke:
|
|
563
|
+
buf.append(b'B\n')
|
|
564
|
+
elif do_fill:
|
|
565
|
+
buf.append(b'f\n')
|
|
566
|
+
else:
|
|
567
|
+
buf.append(b'S\n')
|
|
568
|
+
if fa is not None:
|
|
569
|
+
set_alpha(0)
|
|
570
|
+
elif kind == 'line':
|
|
571
|
+
_, x1, y1, x2, y2, stroke, sw = op
|
|
572
|
+
if stroke is not None:
|
|
573
|
+
buf.append(_rgb(stroke) + b' RG ')
|
|
574
|
+
buf.append(_f(sw) + b' w ')
|
|
575
|
+
buf.append(_f(x1) + b' ' + _f(H - y1) + b' m ')
|
|
576
|
+
buf.append(_f(x2) + b' ' + _f(H - y2) + b' l S\n')
|
|
577
|
+
elif kind == 'lines':
|
|
578
|
+
_, segs, stroke, sw = op
|
|
579
|
+
if stroke is not None:
|
|
580
|
+
buf.append(_rgb(stroke) + b' RG ')
|
|
581
|
+
buf.append(_f(sw) + b' w ')
|
|
582
|
+
x0, y0, _, _ = segs[0]
|
|
583
|
+
buf.append(_f(x0) + b' ' + _f(H - y0) + b' m ')
|
|
584
|
+
for (px, py, qx, qy) in segs:
|
|
585
|
+
buf.append(_f(qx) + b' ' + _f(H - qy) + b' l ')
|
|
586
|
+
buf.append(b'S\n')
|
|
587
|
+
elif kind == 'circle':
|
|
588
|
+
_, cx, cy, r, fill, stroke, sw = op
|
|
589
|
+
if fill is not None or stroke is not None:
|
|
590
|
+
if fill is not None:buf.append(_rgb(fill) + b' rg ')
|
|
591
|
+
if stroke is not None:buf.append(_rgb(stroke)+b' RG '+_f(sw)+b' w ')
|
|
592
|
+
cy = H - cy
|
|
593
|
+
k = r * 0.5522847498
|
|
594
|
+
buf.append(_f(cx + r) + b' ' + _f(cy) + b' m ')
|
|
595
|
+
buf.append(_f(cx + r) + b' ' + _f(cy + k) + b' ' + _f(cx + k) + b' ' + _f(cy + r) + b' ' + _f(cx) + b' ' + _f(cy + r) + b' c ')
|
|
596
|
+
buf.append(_f(cx - k) + b' ' + _f(cy + r) + b' ' + _f(cx - r) + b' ' + _f(cy + k) + b' ' + _f(cx - r) + b' ' + _f(cy) + b' c ')
|
|
597
|
+
buf.append(_f(cx - r) + b' ' + _f(cy - k) + b' ' + _f(cx - k) + b' ' + _f(cy - r) + b' ' + _f(cx) + b' ' + _f(cy - r) + b' c ')
|
|
598
|
+
buf.append(_f(cx + k) + b' ' + _f(cy - r) + b' ' + _f(cx + r) + b' ' + _f(cy - k) + b' ' + _f(cx + r) + b' ' + _f(cy) + b' c h '+(b'B' if fill is not None and stroke is not None else b'f' if fill is not None else b'S')+b'\n')
|
|
599
|
+
elif kind == 'image':
|
|
600
|
+
_, x, y, w, h, png = op
|
|
601
|
+
idx = img_idx[id(op)]
|
|
602
|
+
yp = H - (y + h)
|
|
603
|
+
buf.append(b'q ' + _f(w) + b' 0 0 ' + _f(h) + b' ' + _f(x) + b' ' + _f(yp) + b' cm /Im%d Do Q\n' % (idx + 1))
|
|
604
|
+
elif kind == 'text':
|
|
605
|
+
_, x, y, content, fname, size, rgb, anchor, dbl, rot = op
|
|
606
|
+
if not content:
|
|
607
|
+
continue
|
|
608
|
+
fidx = font_idx[fname] + 1
|
|
609
|
+
if rgb is not None:
|
|
610
|
+
buf.append(_rgb(rgb) + b' rg ')
|
|
611
|
+
else:
|
|
612
|
+
buf.append(b'0 0 0 rg ')
|
|
613
|
+
off = 0.0
|
|
614
|
+
if dbl:
|
|
615
|
+
d = str(dbl).lower()
|
|
616
|
+
if 'middle' in d:
|
|
617
|
+
off = 0.35 * size
|
|
618
|
+
elif 'hanging' in d:
|
|
619
|
+
off = 0.8 * size
|
|
620
|
+
elif 'after' in d:
|
|
621
|
+
off = 0.2 * size
|
|
622
|
+
wpx = _text_width(content, fname, size)
|
|
623
|
+
if anchor == 'end':
|
|
624
|
+
dx = -wpx
|
|
625
|
+
elif anchor == 'middle':
|
|
626
|
+
dx = -wpx / 2.0
|
|
627
|
+
else:
|
|
628
|
+
dx = 0.0
|
|
629
|
+
esc = _pdf_escape(content)
|
|
630
|
+
if rot:
|
|
631
|
+
angle, rcx, rcy = rot
|
|
632
|
+
rad = math.radians(angle)
|
|
633
|
+
ca = math.cos(rad)
|
|
634
|
+
sa = math.sin(rad)
|
|
635
|
+
a = ca
|
|
636
|
+
b = -sa
|
|
637
|
+
c = sa
|
|
638
|
+
d = ca
|
|
639
|
+
e = rcx + ca * dx - sa * off
|
|
640
|
+
f = H - rcy - sa * dx - ca * off
|
|
641
|
+
buf.append(b'BT /F%d %s Tf %s %s %s %s %s %s Tm %s Tj ET\n' % (
|
|
642
|
+
fidx, _f(size), _f(a), _f(b), _f(c), _f(d), _f(e), _f(f), esc))
|
|
643
|
+
else:
|
|
644
|
+
yp = H - (y + off)
|
|
645
|
+
buf.append(b'BT /F%d %s Tf %s %s Td %s Tj ET\n' % (
|
|
646
|
+
fidx, _f(size), _f(x + dx), _f(yp), esc))
|
|
647
|
+
|
|
648
|
+
content_bytes = b''.join(buf)
|
|
649
|
+
content_z = zlib.compress(content_bytes, 6)
|
|
650
|
+
|
|
651
|
+
# ---- assemble the PDF document ----
|
|
652
|
+
n_fonts = len(fonts)
|
|
653
|
+
n_imgs = len(images)
|
|
654
|
+
n_gs = len(alphas)
|
|
655
|
+
img_start = 4 + n_fonts
|
|
656
|
+
gs_start = img_start + n_imgs
|
|
657
|
+
n_objects = 4 + n_fonts + n_imgs + n_gs
|
|
658
|
+
|
|
659
|
+
font_res = b' '.join(
|
|
660
|
+
b'/F%d %d 0 R' % (i + 1, 5 + i) for i in range(n_fonts))
|
|
661
|
+
img_res = b' '.join(
|
|
662
|
+
b'/Im%d %d 0 R' % (i + 1, img_start + i + 1) for i in range(n_imgs))
|
|
663
|
+
gs_res = b' '.join(
|
|
664
|
+
b'/GS%d %d 0 R' % (i, gs_start + i + 1) for i in range(n_gs))
|
|
665
|
+
|
|
666
|
+
resources = b'<< '
|
|
667
|
+
if font_res:
|
|
668
|
+
resources += b'/Font << ' + font_res + b' >> '
|
|
669
|
+
if img_res:
|
|
670
|
+
resources += b'/XObject << ' + img_res + b' >> '
|
|
671
|
+
if gs_res:
|
|
672
|
+
resources += b'/ExtGState << ' + gs_res + b' >> '
|
|
673
|
+
resources += b'>>'
|
|
674
|
+
|
|
675
|
+
objs = []
|
|
676
|
+
objs.append(b'<< /Type /Catalog /Pages 2 0 R >>')
|
|
677
|
+
objs.append(b'<< /Type /Pages /Kids [3 0 R] /Count 1 >>')
|
|
678
|
+
objs.append(b'<< /Type /Page /Parent 2 0 R /MediaBox [0 0 %s %s] /Resources %s /Contents 4 0 R >>' % (_f(W), _f(H), resources))
|
|
679
|
+
objs.append(b'<< /Length %d /Filter /FlateDecode >>\nstream\n%s\nendstream' % (len(content_z), content_z))
|
|
680
|
+
for fn in fonts:
|
|
681
|
+
objs.append(b'<< /Type /Font /Subtype /Type1 /BaseFont %s /Encoding /WinAnsiEncoding >>' % _FONT_OBJ[fn].encode('ascii'))
|
|
682
|
+
for op in images:
|
|
683
|
+
_, x, y, w, h, payload = op
|
|
684
|
+
if isinstance(payload, _IndexedImage):
|
|
685
|
+
data = zlib.compress(payload.indices, 6)
|
|
686
|
+
cs = b'[/Indexed /DeviceRGB 255 <' + payload.palette_hex + b'>]'
|
|
687
|
+
objs.append(
|
|
688
|
+
b'<< /Type /XObject /Subtype /Image /Width %d /Height %d /ColorSpace %s '
|
|
689
|
+
b'/BitsPerComponent 8 /Filter /FlateDecode /Length %d >>\nstream\n%s\nendstream'
|
|
690
|
+
% (payload.width, payload.height, cs, len(data), data))
|
|
691
|
+
continue
|
|
692
|
+
rgb, pw, ph = self._png_to_rgb(payload)
|
|
693
|
+
data = zlib.compress(rgb, 6)
|
|
694
|
+
objs.append(
|
|
695
|
+
b'<< /Type /XObject /Subtype /Image /Width %d /Height %d /ColorSpace /DeviceRGB '
|
|
696
|
+
b'/BitsPerComponent 8 /Filter /FlateDecode /Length %d >>\nstream\n%s\nendstream'
|
|
697
|
+
% (pw, ph, len(data), data))
|
|
698
|
+
for a in alphas:
|
|
699
|
+
objs.append(b'<< /Type /ExtGState /ca %s >>' % _f(a))
|
|
700
|
+
|
|
701
|
+
out = [b'%PDF-1.4\n%\xe2\xe3\xcf\xd3\n']
|
|
702
|
+
offsets = []
|
|
703
|
+
for i, obj in enumerate(objs):
|
|
704
|
+
offsets.append(sum(len(p) for p in out))
|
|
705
|
+
out.append(b'%d 0 obj\n' % (i + 1))
|
|
706
|
+
out.append(obj)
|
|
707
|
+
out.append(b'\nendobj\n')
|
|
708
|
+
xref_pos = sum(len(p) for p in out)
|
|
709
|
+
out.append(b'xref\n0 %d\n' % (n_objects + 1))
|
|
710
|
+
out.append(b'0000000000 65535 f \n')
|
|
711
|
+
for off in offsets:
|
|
712
|
+
out.append(b'%010d 00000 n \n' % off)
|
|
713
|
+
out.append(b'trailer\n<< /Size %d /Root 1 0 R >>\n' % (n_objects + 1))
|
|
714
|
+
out.append(b'startxref\n%d\n%%%%EOF\n' % xref_pos)
|
|
715
|
+
|
|
716
|
+
with open(output_path, 'wb') as fh:
|
|
717
|
+
fh.write(b''.join(out))
|