Inkfish-Sepia 0.2.0__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.
Sepia/__init__.py
ADDED
Sepia/core.py
ADDED
|
@@ -0,0 +1,511 @@
|
|
|
1
|
+
"""Create flowcharts from Python, or run this file to open the desktop editor."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
from collections import deque
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from io import BytesIO
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from xml.sax.saxutils import escape
|
|
12
|
+
|
|
13
|
+
from PIL import Image, ImageDraw, ImageFont
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
DEFAULT_COLORS = {
|
|
17
|
+
"start": ("#b8e7dd", "#c6efc1"),
|
|
18
|
+
"end": ("#b8e7dd", "#c6efc1"),
|
|
19
|
+
"process": ("#d1ebfa", "#a9d8f6"),
|
|
20
|
+
"decision": ("#ffe2b6", "#ffd0a5"),
|
|
21
|
+
"input_output": ("#e4d7f8", "#d2c4f2"),
|
|
22
|
+
"document": ("#fff2bd", "#ffe4a3"),
|
|
23
|
+
"subprocess": ("#cce8f6", "#a8d7f0"),
|
|
24
|
+
"database": ("#f8dce9", "#edc5e0"),
|
|
25
|
+
"preparation": ("#ffdfc5", "#ffcaab"),
|
|
26
|
+
"connector": ("#c5ece6", "#b6e6d6"),
|
|
27
|
+
}
|
|
28
|
+
KINDS = tuple(DEFAULT_COLORS)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _validate_color(color: str) -> str:
|
|
32
|
+
if not isinstance(color, str) or len(color) != 7 or color[0] != "#":
|
|
33
|
+
raise ValueError("Colors must be in #RRGGBB format.")
|
|
34
|
+
try:
|
|
35
|
+
int(color[1:], 16)
|
|
36
|
+
except ValueError as exc:
|
|
37
|
+
raise ValueError("Colors must be in #RRGGBB format.") from exc
|
|
38
|
+
return color.lower()
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass
|
|
42
|
+
class Block:
|
|
43
|
+
id: str
|
|
44
|
+
kind: str
|
|
45
|
+
text: str
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass
|
|
49
|
+
class Connection:
|
|
50
|
+
source: str
|
|
51
|
+
target: str
|
|
52
|
+
label: str = ""
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass
|
|
56
|
+
class Flowchart:
|
|
57
|
+
blocks: list[Block] = field(default_factory=list)
|
|
58
|
+
connections: list[Connection] = field(default_factory=list)
|
|
59
|
+
colors: dict[str, tuple[str, str]] = field(
|
|
60
|
+
default_factory=lambda: DEFAULT_COLORS.copy()
|
|
61
|
+
)
|
|
62
|
+
title: str = ""
|
|
63
|
+
|
|
64
|
+
def add_block(self, id: str, kind: str, text: str) -> Block:
|
|
65
|
+
if not isinstance(id, str) or not id.strip():
|
|
66
|
+
raise ValueError("A block ID is required.")
|
|
67
|
+
if any(block.id == id for block in self.blocks):
|
|
68
|
+
raise ValueError(f"Block ID {id!r} already exists.")
|
|
69
|
+
if kind not in KINDS:
|
|
70
|
+
raise ValueError(f"Unknown block type: {kind!r}.")
|
|
71
|
+
if not isinstance(text, str) or not text.strip():
|
|
72
|
+
raise ValueError("Block text is required.")
|
|
73
|
+
block = Block(id, kind, text)
|
|
74
|
+
self.blocks.append(block)
|
|
75
|
+
return block
|
|
76
|
+
|
|
77
|
+
def connect(self, source: str, target: str, label: str = "") -> Connection:
|
|
78
|
+
ids = {block.id for block in self.blocks}
|
|
79
|
+
if source not in ids or target not in ids:
|
|
80
|
+
raise ValueError("Both connection endpoints must be existing block IDs.")
|
|
81
|
+
if not isinstance(label, str):
|
|
82
|
+
raise ValueError("The connection label must be text.")
|
|
83
|
+
edge = Connection(source, target, label)
|
|
84
|
+
self.connections.append(edge)
|
|
85
|
+
return edge
|
|
86
|
+
|
|
87
|
+
def set_colors(self, kind: str, top: str, bottom: str) -> None:
|
|
88
|
+
if kind not in KINDS:
|
|
89
|
+
raise ValueError(f"Unknown block type: {kind!r}.")
|
|
90
|
+
self.colors[kind] = (_validate_color(top), _validate_color(bottom))
|
|
91
|
+
|
|
92
|
+
def to_dict(self) -> dict:
|
|
93
|
+
return {
|
|
94
|
+
"version": 1,
|
|
95
|
+
"title": self.title,
|
|
96
|
+
"blocks": [vars(block).copy() for block in self.blocks],
|
|
97
|
+
"connections": [vars(edge).copy() for edge in self.connections],
|
|
98
|
+
"colors": {kind: list(colors) for kind, colors in self.colors.items()},
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
@classmethod
|
|
102
|
+
def from_dict(cls, data: dict) -> Flowchart:
|
|
103
|
+
if not isinstance(data, dict) or data.get("version") != 1:
|
|
104
|
+
raise ValueError("Unsupported or invalid flowchart file.")
|
|
105
|
+
chart = cls()
|
|
106
|
+
try:
|
|
107
|
+
title = data.get("title", "")
|
|
108
|
+
if not isinstance(title, str):
|
|
109
|
+
raise ValueError("The chart title must be text.")
|
|
110
|
+
chart.title = title
|
|
111
|
+
for kind, colors in data.get("colors", {}).items():
|
|
112
|
+
if not isinstance(colors, (list, tuple)) or len(colors) != 2:
|
|
113
|
+
raise ValueError(f"Expected two colors for {kind!r}.")
|
|
114
|
+
chart.set_colors(kind, colors[0], colors[1])
|
|
115
|
+
for block in data["blocks"]:
|
|
116
|
+
chart.add_block(block["id"], block["kind"], block["text"])
|
|
117
|
+
for edge in data["connections"]:
|
|
118
|
+
chart.connect(edge["source"], edge["target"], edge.get("label", ""))
|
|
119
|
+
except (KeyError, TypeError, AttributeError) as exc:
|
|
120
|
+
raise ValueError(f"Invalid flowchart file: {exc}") from exc
|
|
121
|
+
return chart
|
|
122
|
+
|
|
123
|
+
def save(self, path: str | Path) -> None:
|
|
124
|
+
Path(path).write_text(
|
|
125
|
+
json.dumps(self.to_dict(), ensure_ascii=False, indent=2), encoding="utf-8"
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
@classmethod
|
|
129
|
+
def load(cls, path: str | Path) -> Flowchart:
|
|
130
|
+
return cls.from_dict(json.loads(Path(path).read_text(encoding="utf-8")))
|
|
131
|
+
|
|
132
|
+
def export(self, path: str | Path) -> None:
|
|
133
|
+
path = Path(path)
|
|
134
|
+
if path.suffix.lower() not in (".svg", ".png"):
|
|
135
|
+
raise ValueError("Export filename must end in .svg or .png.")
|
|
136
|
+
renderer = Renderer(self)
|
|
137
|
+
if path.suffix.lower() == ".svg":
|
|
138
|
+
path.write_text(renderer.svg(), encoding="utf-8")
|
|
139
|
+
else:
|
|
140
|
+
renderer.image().save(path, format="PNG")
|
|
141
|
+
|
|
142
|
+
def render_svg(self) -> str:
|
|
143
|
+
return Renderer(self).svg()
|
|
144
|
+
|
|
145
|
+
def render_png(self) -> bytes:
|
|
146
|
+
output = BytesIO()
|
|
147
|
+
Renderer(self).image().save(output, format="PNG")
|
|
148
|
+
return output.getvalue()
|
|
149
|
+
|
|
150
|
+
def render_preview(self) -> Image.Image:
|
|
151
|
+
return Renderer(self).image()
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _font(size: int) -> ImageFont.FreeTypeFont:
|
|
155
|
+
# Prefer widely available Unicode-capable system fonts.
|
|
156
|
+
candidates = [
|
|
157
|
+
Path(os.environ.get("WINDIR", "C:\\Windows")) / "Fonts" / "arial.ttf",
|
|
158
|
+
Path(os.environ.get("WINDIR", "C:\\Windows")) / "Fonts" / "seguisym.ttf",
|
|
159
|
+
Path("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"),
|
|
160
|
+
Path("/System/Library/Fonts/Supplemental/Arial Unicode.ttf"),
|
|
161
|
+
]
|
|
162
|
+
for candidate in candidates:
|
|
163
|
+
if candidate.is_file():
|
|
164
|
+
return ImageFont.truetype(str(candidate), size)
|
|
165
|
+
raise RuntimeError("No supported Unicode font found (Arial or DejaVu Sans).")
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _wrap(text: str, font: ImageFont.FreeTypeFont, width: int) -> list[str]:
|
|
169
|
+
lines = []
|
|
170
|
+
for paragraph in text.split("\n"):
|
|
171
|
+
if not paragraph:
|
|
172
|
+
lines.append("")
|
|
173
|
+
continue
|
|
174
|
+
current = ""
|
|
175
|
+
for word in paragraph.split():
|
|
176
|
+
candidate = f"{current} {word}".strip()
|
|
177
|
+
if font.getlength(candidate) <= width:
|
|
178
|
+
current = candidate
|
|
179
|
+
continue
|
|
180
|
+
if current:
|
|
181
|
+
lines.append(current)
|
|
182
|
+
current = ""
|
|
183
|
+
for char in word:
|
|
184
|
+
if current and font.getlength(current + char) > width:
|
|
185
|
+
lines.append(current)
|
|
186
|
+
current = ""
|
|
187
|
+
current += char
|
|
188
|
+
lines.append(current)
|
|
189
|
+
return lines or [""]
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
class Renderer:
|
|
193
|
+
FONT_SIZE = 16
|
|
194
|
+
BLOCK_WIDTH = 240
|
|
195
|
+
GAP_X = 70
|
|
196
|
+
GAP_Y = 100
|
|
197
|
+
MARGIN = 45
|
|
198
|
+
TITLE_SIZE = 30
|
|
199
|
+
TITLE_LINE_HEIGHT = 42
|
|
200
|
+
CORNER_RADIUS = 16
|
|
201
|
+
|
|
202
|
+
def __init__(self, chart: Flowchart):
|
|
203
|
+
if not chart.blocks:
|
|
204
|
+
raise ValueError("Add at least one block before exporting or previewing.")
|
|
205
|
+
self.chart = chart
|
|
206
|
+
self.font = _font(self.FONT_SIZE)
|
|
207
|
+
self.label_font = _font(14)
|
|
208
|
+
if not isinstance(chart.title, str):
|
|
209
|
+
raise ValueError("The chart title must be text.")
|
|
210
|
+
self.title_font = _font(self.TITLE_SIZE)
|
|
211
|
+
self.title_lines = []
|
|
212
|
+
self.edge_lines = [_wrap(edge.label, self.label_font, 180)
|
|
213
|
+
for edge in chart.connections]
|
|
214
|
+
self.gap_y = max(self.GAP_Y, max(
|
|
215
|
+
(len(lines) * 18 + 60 for lines in self.edge_lines), default=0
|
|
216
|
+
))
|
|
217
|
+
self.lines = {}
|
|
218
|
+
self.sizes = {}
|
|
219
|
+
for block in chart.blocks:
|
|
220
|
+
width = 56 if block.kind == "connector" else self.BLOCK_WIDTH
|
|
221
|
+
text_width = 44 if block.kind == "connector" else 140 if block.kind == "decision" else 185
|
|
222
|
+
lines = _wrap(block.text, self.font, text_width)
|
|
223
|
+
height = 56 if block.kind == "connector" else max(80, len(lines) * 22 + 36)
|
|
224
|
+
if block.kind == "decision":
|
|
225
|
+
height = max(120, len(lines) * 40 + 48)
|
|
226
|
+
self.lines[block.id] = lines
|
|
227
|
+
self.sizes[block.id] = (width, height)
|
|
228
|
+
self.positions, self.width, self.height, self.levels, self.row_bounds = self._layout()
|
|
229
|
+
self.routes = self._routes()
|
|
230
|
+
|
|
231
|
+
def _layout(self):
|
|
232
|
+
ids = [block.id for block in self.chart.blocks]
|
|
233
|
+
outgoing = {id: [] for id in ids}
|
|
234
|
+
incoming = {id: 0 for id in ids}
|
|
235
|
+
for edge in self.chart.connections:
|
|
236
|
+
outgoing[edge.source].append(edge.target)
|
|
237
|
+
incoming[edge.target] += 1
|
|
238
|
+
# Remove depth-first back edges before assigning levels. This keeps
|
|
239
|
+
# joins below all of their forward predecessors, even in cyclic charts.
|
|
240
|
+
roots = [id for id in ids if incoming[id] == 0]
|
|
241
|
+
states = {id: 0 for id in ids}
|
|
242
|
+
forward = {id: [] for id in ids}
|
|
243
|
+
for root in roots + ids:
|
|
244
|
+
if states[root]:
|
|
245
|
+
continue
|
|
246
|
+
states[root] = 1
|
|
247
|
+
stack = [(root, iter(outgoing[root]))]
|
|
248
|
+
while stack:
|
|
249
|
+
node, targets = stack[-1]
|
|
250
|
+
target = next(targets, None)
|
|
251
|
+
if target is None:
|
|
252
|
+
states[node] = 2
|
|
253
|
+
stack.pop()
|
|
254
|
+
elif states[target] != 1:
|
|
255
|
+
forward[node].append(target)
|
|
256
|
+
if states[target] == 0:
|
|
257
|
+
states[target] = 1
|
|
258
|
+
stack.append((target, iter(outgoing[target])))
|
|
259
|
+
forward_incoming = {id: 0 for id in ids}
|
|
260
|
+
for targets in forward.values():
|
|
261
|
+
for target in targets:
|
|
262
|
+
forward_incoming[target] += 1
|
|
263
|
+
levels = {id: 0 for id in ids}
|
|
264
|
+
queue = deque(id for id in ids if forward_incoming[id] == 0)
|
|
265
|
+
while queue:
|
|
266
|
+
node = queue.popleft()
|
|
267
|
+
for target in forward[node]:
|
|
268
|
+
levels[target] = max(levels[target], levels[node] + 1)
|
|
269
|
+
forward_incoming[target] -= 1
|
|
270
|
+
if forward_incoming[target] == 0:
|
|
271
|
+
queue.append(target)
|
|
272
|
+
rows = {}
|
|
273
|
+
for id in ids:
|
|
274
|
+
rows.setdefault(levels[id], []).append(id)
|
|
275
|
+
content_width = max(
|
|
276
|
+
sum(self.sizes[id][0] for id in row) + (len(row) - 1) * self.GAP_X
|
|
277
|
+
for row in rows.values()
|
|
278
|
+
)
|
|
279
|
+
positions = {}
|
|
280
|
+
row_bounds = {}
|
|
281
|
+
y = self.MARGIN
|
|
282
|
+
if self.chart.title.strip():
|
|
283
|
+
self.title_lines = _wrap(self.chart.title, self.title_font, content_width)
|
|
284
|
+
y += len(self.title_lines) * self.TITLE_LINE_HEIGHT + 30
|
|
285
|
+
for level in sorted(rows):
|
|
286
|
+
row = rows[level]
|
|
287
|
+
row_width = (
|
|
288
|
+
sum(self.sizes[id][0] for id in row)
|
|
289
|
+
+ (len(row) - 1) * self.GAP_X
|
|
290
|
+
)
|
|
291
|
+
x = self.MARGIN + (content_width - row_width) / 2
|
|
292
|
+
row_height = max(self.sizes[id][1] for id in row)
|
|
293
|
+
row_bounds[level] = (y, y + row_height)
|
|
294
|
+
for id in row:
|
|
295
|
+
positions[id] = (x, y + (row_height - self.sizes[id][1]) / 2)
|
|
296
|
+
x += self.sizes[id][0] + self.GAP_X
|
|
297
|
+
y += row_height + self.gap_y
|
|
298
|
+
# Reserve a separate outside lane for each long or backward connection.
|
|
299
|
+
outside = len({
|
|
300
|
+
self._outside_key(index, edge, levels)
|
|
301
|
+
for index, edge in enumerate(self.chart.connections)
|
|
302
|
+
if levels[edge.target] != levels[edge.source] + 1
|
|
303
|
+
})
|
|
304
|
+
width = self.MARGIN * 2 + content_width + outside * 24 + (30 if outside else 0)
|
|
305
|
+
if any(edge.label for edge in self.chart.connections):
|
|
306
|
+
width += 100
|
|
307
|
+
bottom_padding = self.gap_y // 2 if outside else 0
|
|
308
|
+
return positions, int(width), int(y - self.gap_y + self.MARGIN + bottom_padding), levels, row_bounds
|
|
309
|
+
|
|
310
|
+
@staticmethod
|
|
311
|
+
def _outside_key(index, edge, levels):
|
|
312
|
+
if not edge.label and levels[edge.target] <= levels[edge.source]:
|
|
313
|
+
return ("return", edge.target, levels[edge.source])
|
|
314
|
+
return ("edge", index)
|
|
315
|
+
|
|
316
|
+
def _routes(self):
|
|
317
|
+
routes = []
|
|
318
|
+
outside_lanes = {}
|
|
319
|
+
content_right = max(
|
|
320
|
+
self.positions[id][0] + self.sizes[id][0] for id in self.positions
|
|
321
|
+
)
|
|
322
|
+
for index, (edge, lines) in enumerate(zip(self.chart.connections, self.edge_lines)):
|
|
323
|
+
sx, sy = self.positions[edge.source]
|
|
324
|
+
tx, ty = self.positions[edge.target]
|
|
325
|
+
sw, sh = self.sizes[edge.source]
|
|
326
|
+
tw, _ = self.sizes[edge.target]
|
|
327
|
+
start = (sx + sw / 2, sy + sh)
|
|
328
|
+
end = (tx + tw / 2, ty)
|
|
329
|
+
if self.levels[edge.target] == self.levels[edge.source] + 1:
|
|
330
|
+
mid = (self.row_bounds[self.levels[edge.source]][1]
|
|
331
|
+
+ self.row_bounds[self.levels[edge.target]][0]) / 2
|
|
332
|
+
points = [start, (start[0], mid), (end[0], mid), end]
|
|
333
|
+
label_at = ((start[0] + end[0]) / 2, mid - 7 - (len(lines) - 1) * 9)
|
|
334
|
+
if start[0] == end[0] and edge.label:
|
|
335
|
+
label_width = max(self.label_font.getlength(line) for line in lines)
|
|
336
|
+
label_at = (start[0] + label_width / 2 + 10, label_at[1])
|
|
337
|
+
else:
|
|
338
|
+
key = self._outside_key(index, edge, self.levels)
|
|
339
|
+
if key not in outside_lanes:
|
|
340
|
+
outside_lanes[key] = content_right + 30 + len(outside_lanes) * 24
|
|
341
|
+
lane = outside_lanes[key]
|
|
342
|
+
exit_y = self.row_bounds[self.levels[edge.source]][1] + self.gap_y / 2
|
|
343
|
+
entry_y = self.row_bounds[self.levels[edge.target]][0] - 25
|
|
344
|
+
source_has_right_neighbor = any(
|
|
345
|
+
self.levels[id] == self.levels[edge.source]
|
|
346
|
+
and self.positions[id][0] > sx
|
|
347
|
+
for id in self.positions
|
|
348
|
+
)
|
|
349
|
+
if (self.levels[edge.target] > self.levels[edge.source] + 1
|
|
350
|
+
and not source_has_right_neighbor):
|
|
351
|
+
source_block = next(block for block in self.chart.blocks
|
|
352
|
+
if block.id == edge.source)
|
|
353
|
+
side_x = sx + sw - (12.5 if source_block.kind == "input_output" else 0)
|
|
354
|
+
start = (side_x, sy + sh / 2)
|
|
355
|
+
points = [start, (lane, start[1]), (lane, entry_y),
|
|
356
|
+
(end[0], entry_y), end]
|
|
357
|
+
label_at = ((start[0] + lane) / 2,
|
|
358
|
+
start[1] - 7 - (len(lines) - 1) * 9)
|
|
359
|
+
else:
|
|
360
|
+
points = [start, (start[0], exit_y), (lane, exit_y),
|
|
361
|
+
(lane, entry_y), (end[0], entry_y), end]
|
|
362
|
+
label_at = ((start[0] + lane) / 2, exit_y - 7 - (len(lines) - 1) * 9)
|
|
363
|
+
routes.append((edge, points, label_at, "\n".join(lines)))
|
|
364
|
+
return routes
|
|
365
|
+
|
|
366
|
+
def _shape(self, block: Block):
|
|
367
|
+
x, y = self.positions[block.id]
|
|
368
|
+
w, h = self.sizes[block.id]
|
|
369
|
+
kind = block.kind
|
|
370
|
+
if kind in ("start", "end"):
|
|
371
|
+
return "capsule", (x, y, x + w, y + h)
|
|
372
|
+
if kind == "connector":
|
|
373
|
+
return "ellipse", (x, y, x + w, y + h)
|
|
374
|
+
if kind == "decision":
|
|
375
|
+
return "polygon", [(x + w / 2, y), (x + w, y + h / 2),
|
|
376
|
+
(x + w / 2, y + h), (x, y + h / 2)]
|
|
377
|
+
if kind == "input_output":
|
|
378
|
+
return "polygon", [(x + 25, y), (x + w, y), (x + w - 25, y + h), (x, y + h)]
|
|
379
|
+
if kind == "preparation":
|
|
380
|
+
return "polygon", [(x + 30, y), (x + w - 30, y), (x + w, y + h / 2),
|
|
381
|
+
(x + w - 30, y + h), (x + 30, y + h), (x, y + h / 2)]
|
|
382
|
+
if kind == "document":
|
|
383
|
+
return "polygon", [(x, y), (x + w, y), (x + w, y + h - 10),
|
|
384
|
+
(x + w * .75, y + h), (x + w * .5, y + h - 10),
|
|
385
|
+
(x + w * .25, y + h), (x, y + h - 10)]
|
|
386
|
+
if kind in ("process", "subprocess"):
|
|
387
|
+
return "rounded_rect", (x, y, x + w, y + h)
|
|
388
|
+
return "rect", (x, y, x + w, y + h)
|
|
389
|
+
|
|
390
|
+
def _radius(self, shape, block):
|
|
391
|
+
if shape == "capsule":
|
|
392
|
+
return min(self.sizes[block.id]) / 2
|
|
393
|
+
return self.CORNER_RADIUS
|
|
394
|
+
|
|
395
|
+
def image(self) -> Image.Image:
|
|
396
|
+
image = Image.new("RGBA", (self.width, self.height), (0, 0, 0, 0))
|
|
397
|
+
draw = ImageDraw.Draw(image)
|
|
398
|
+
for index, line in enumerate(self.title_lines):
|
|
399
|
+
draw.text((self.MARGIN, self.MARGIN + index * self.TITLE_LINE_HEIGHT),
|
|
400
|
+
line, fill="#17283c", font=self.title_font, anchor="la")
|
|
401
|
+
for edge, points, label, wrapped_label in self.routes:
|
|
402
|
+
draw.line(points, fill="#46546b", width=2, joint="curve")
|
|
403
|
+
ex, ey = points[-1]
|
|
404
|
+
draw.polygon([(ex, ey), (ex - 6, ey - 11), (ex + 6, ey - 11)], fill="#46546b")
|
|
405
|
+
if edge.label:
|
|
406
|
+
draw.multiline_text(label, wrapped_label, font=self.label_font,
|
|
407
|
+
fill="#273447", anchor="ms", align="center")
|
|
408
|
+
for block in self.chart.blocks:
|
|
409
|
+
shape, coords = self._shape(block)
|
|
410
|
+
pillow_shape = ("rounded_rectangle" if shape in ("capsule", "rounded_rect")
|
|
411
|
+
else "rectangle" if shape == "rect" else shape)
|
|
412
|
+
mask = Image.new("L", image.size, 0)
|
|
413
|
+
mask_draw = ImageDraw.Draw(mask)
|
|
414
|
+
options = {"radius": self._radius(shape, block)} if pillow_shape == "rounded_rectangle" else {}
|
|
415
|
+
getattr(mask_draw, pillow_shape)(coords, fill=255, **options)
|
|
416
|
+
x, y = self.positions[block.id]
|
|
417
|
+
w, h = self.sizes[block.id]
|
|
418
|
+
left, right = self.chart.colors[block.kind]
|
|
419
|
+
a = tuple(bytes.fromhex(left[1:]))
|
|
420
|
+
b = tuple(bytes.fromhex(right[1:]))
|
|
421
|
+
gradient = Image.new("RGBA", image.size)
|
|
422
|
+
gd = ImageDraw.Draw(gradient)
|
|
423
|
+
for step in range(int(w) + 1):
|
|
424
|
+
t = step / w
|
|
425
|
+
color = tuple(round(a[i] * (1 - t) + b[i] * t) for i in range(3)) + (255,)
|
|
426
|
+
gd.line((x + step, y, x + step, y + h), fill=color)
|
|
427
|
+
image.paste(gradient, (0, 0), mask)
|
|
428
|
+
draw = ImageDraw.Draw(image)
|
|
429
|
+
self._image_details(draw, block)
|
|
430
|
+
lines = self.lines[block.id]
|
|
431
|
+
first_y = y + h / 2 - (len(lines) - 1) * 11
|
|
432
|
+
for index, line in enumerate(lines):
|
|
433
|
+
draw.text((x + w / 2, first_y + index * 22), line,
|
|
434
|
+
fill="#17283c", font=self.font, anchor="mm")
|
|
435
|
+
return image
|
|
436
|
+
|
|
437
|
+
def _image_details(self, draw, block):
|
|
438
|
+
x, y = self.positions[block.id]
|
|
439
|
+
w, h = self.sizes[block.id]
|
|
440
|
+
if block.kind == "subprocess":
|
|
441
|
+
for offset in (15, w - 15):
|
|
442
|
+
draw.line((x + offset, y, x + offset, y + h), fill="#60768b", width=2)
|
|
443
|
+
elif block.kind == "database":
|
|
444
|
+
draw.arc((x, y - 10, x + w, y + 10), 0, 180, fill="#60768b", width=2)
|
|
445
|
+
draw.arc((x, y + h - 20, x + w, y + h), 0, 180, fill="#60768b", width=2)
|
|
446
|
+
|
|
447
|
+
def svg(self) -> str:
|
|
448
|
+
parts = [
|
|
449
|
+
f'<svg xmlns="http://www.w3.org/2000/svg" width="{self.width}" height="{self.height}" '
|
|
450
|
+
f'viewBox="0 0 {self.width} {self.height}">',
|
|
451
|
+
"<defs>",
|
|
452
|
+
]
|
|
453
|
+
for index, block in enumerate(self.chart.blocks):
|
|
454
|
+
left, right = self.chart.colors[block.kind]
|
|
455
|
+
parts.append(
|
|
456
|
+
f'<linearGradient id="g{index}" x1="0%" y1="0%" x2="100%" y2="0%">'
|
|
457
|
+
f'<stop offset="0%" stop-color="{left}"/>'
|
|
458
|
+
f'<stop offset="100%" stop-color="{right}"/></linearGradient>'
|
|
459
|
+
)
|
|
460
|
+
parts.append("</defs>")
|
|
461
|
+
ascent, _ = self.title_font.getmetrics()
|
|
462
|
+
for index, line in enumerate(self.title_lines):
|
|
463
|
+
parts.append(
|
|
464
|
+
f'<text x="{self.MARGIN}" y="{self.MARGIN + ascent + index * self.TITLE_LINE_HEIGHT}" '
|
|
465
|
+
f'fill="#17283c" font-family="Arial, DejaVu Sans, sans-serif" '
|
|
466
|
+
f'font-size="{self.TITLE_SIZE}">{escape(line)}</text>'
|
|
467
|
+
)
|
|
468
|
+
for edge, points, label, wrapped_label in self.routes:
|
|
469
|
+
path = " ".join(f"{x:.1f},{y:.1f}" for x, y in points)
|
|
470
|
+
parts.append(f'<polyline points="{path}" fill="none" stroke="#46546b" stroke-width="2"/>')
|
|
471
|
+
ex, ey = points[-1]
|
|
472
|
+
parts.append(f'<polygon points="{ex},{ey} {ex-6},{ey-11} {ex+6},{ey-11}" fill="#46546b"/>')
|
|
473
|
+
if edge.label:
|
|
474
|
+
parts.append(self._svg_text(label[0], label[1], wrapped_label, 14))
|
|
475
|
+
for index, block in enumerate(self.chart.blocks):
|
|
476
|
+
shape, coords = self._shape(block)
|
|
477
|
+
style = f'fill="url(#g{index})"'
|
|
478
|
+
x, y = self.positions[block.id]
|
|
479
|
+
w, h = self.sizes[block.id]
|
|
480
|
+
if shape == "polygon":
|
|
481
|
+
points = " ".join(f"{px},{py}" for px, py in coords)
|
|
482
|
+
parts.append(f'<polygon points="{points}" {style}/>')
|
|
483
|
+
elif shape == "ellipse":
|
|
484
|
+
parts.append(f'<ellipse cx="{x+w/2}" cy="{y+h/2}" rx="{w/2}" ry="{h/2}" {style}/>')
|
|
485
|
+
else:
|
|
486
|
+
radius = self._radius(shape, block) if shape in ("capsule", "rounded_rect") else 0
|
|
487
|
+
parts.append(f'<rect x="{x}" y="{y}" width="{w}" height="{h}" rx="{radius}" {style}/>')
|
|
488
|
+
if block.kind == "subprocess":
|
|
489
|
+
for offset in (15, w - 15):
|
|
490
|
+
parts.append(f'<line x1="{x+offset}" y1="{y}" x2="{x+offset}" y2="{y+h}" stroke="#60768b" stroke-width="2"/>')
|
|
491
|
+
elif block.kind == "database":
|
|
492
|
+
parts.append(f'<path d="M {x} {y} Q {x+w/2} {y+20} {x+w} {y} M {x} {y+h-10} Q {x+w/2} {y+h+10} {x+w} {y+h-10}" fill="none" stroke="#60768b" stroke-width="2"/>')
|
|
493
|
+
first_y = y + h / 2 - (len(self.lines[block.id]) - 1) * 11 + 5
|
|
494
|
+
for line_index, line in enumerate(self.lines[block.id]):
|
|
495
|
+
parts.append(self._svg_text(x + w / 2, first_y + line_index * 22, line, 16))
|
|
496
|
+
parts.append("</svg>")
|
|
497
|
+
return "\n".join(parts)
|
|
498
|
+
|
|
499
|
+
@staticmethod
|
|
500
|
+
def _svg_text(x, y, text, size):
|
|
501
|
+
# Preserve multiline edge labels without interpreting them as markup.
|
|
502
|
+
lines = text.split("\n")
|
|
503
|
+
spans = "".join(
|
|
504
|
+
f'<tspan x="{x}" dy="{0 if i == 0 else size + 3}">{escape(line)}</tspan>'
|
|
505
|
+
for i, line in enumerate(lines)
|
|
506
|
+
)
|
|
507
|
+
return (f'<text x="{x}" y="{y}" text-anchor="middle" fill="#17283c" '
|
|
508
|
+
f'font-family="Arial, DejaVu Sans, sans-serif" font-size="{size}">{spans}</text>')
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
_Renderer = Renderer
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: Inkfish-Sepia
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Reusable Python flowchart model with SVG and PNG rendering
|
|
5
|
+
Author: iancullinane06
|
|
6
|
+
Project-URL: Homepage, https://inkfish-labs.github.io/
|
|
7
|
+
Project-URL: Documentation, https://inkfish-labs.github.io/
|
|
8
|
+
Keywords: flowchart,diagram,Inkfish,rendering,svg,png
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
19
|
+
Classifier: Topic :: Scientific/Engineering :: Visualization
|
|
20
|
+
Classifier: Operating System :: OS Independent
|
|
21
|
+
Requires-Python: >=3.9
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
Requires-Dist: Pillow>=10.0
|
|
24
|
+
Provides-Extra: dev
|
|
25
|
+
Requires-Dist: build>=1.2; extra == "dev"
|
|
26
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
27
|
+
Requires-Dist: python-dotenv>=1.0; extra == "dev"
|
|
28
|
+
Requires-Dist: twine>=5; extra == "dev"
|
|
29
|
+
|
|
30
|
+
# Inkfish Labs Sepia API
|
|
31
|
+
|
|
32
|
+
Reusable Python flowchart model with SVG and PNG rendering.
|
|
33
|
+
|
|
34
|
+
## Install
|
|
35
|
+
|
|
36
|
+
```powershell
|
|
37
|
+
python -m pip install
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
For development:
|
|
41
|
+
|
|
42
|
+
```powershell
|
|
43
|
+
python -m pip install -e .[dev]
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Python API
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
from Sepia import Flowchart
|
|
50
|
+
|
|
51
|
+
chart = Flowchart()
|
|
52
|
+
chart.add_block("start", "start", "Start")
|
|
53
|
+
svg = chart.render_svg()
|
|
54
|
+
png = chart.render_png()
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Tests
|
|
58
|
+
|
|
59
|
+
```powershell
|
|
60
|
+
python -m pytest
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Build for PyPI
|
|
64
|
+
|
|
65
|
+
```powershell
|
|
66
|
+
python -m build
|
|
67
|
+
python -m twine check --strict dist\*
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Upload a release only after testing the wheel:
|
|
71
|
+
|
|
72
|
+
```powershell
|
|
73
|
+
python -m twine upload --repository testpypi dist\*
|
|
74
|
+
python -m twine upload dist\*
|
|
75
|
+
```
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
Sepia/__init__.py,sha256=WiiaMV5hrPu3E74hLF6Tm0FEKW9koVDS8YqgVGlFi8M,265
|
|
2
|
+
Sepia/core.py,sha256=z7KcHjlYnULUvOQYFdESUnGXaNYDydkCBDA52x-9ewE,23224
|
|
3
|
+
inkfish_sepia-0.2.0.dist-info/METADATA,sha256=nNdX59mX-5MDOyVB0M6gk3H5vvMug5_C0EgFLLcqcLU,1957
|
|
4
|
+
inkfish_sepia-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
5
|
+
inkfish_sepia-0.2.0.dist-info/top_level.txt,sha256=qiotAUUcVb0lo3bhfsUHNx87RvRwqMkgmmHyOBrtAtI,6
|
|
6
|
+
inkfish_sepia-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
Sepia
|