|
9 | 9 | (https://en.wikipedia.org/wiki/Finite-state_machine)
|
10 | 10 | """
|
11 | 11 |
|
| 12 | +import string |
| 13 | +from urllib.request import urlopen, Request |
| 14 | +from base64 import b64encode |
| 15 | +from zlib import compress |
| 16 | +from io import BytesIO |
12 | 17 | from collections.abc import Callable
|
| 18 | +from matplotlib.image import imread |
| 19 | +from matplotlib import pyplot as plt |
| 20 | + |
| 21 | + |
| 22 | +def deflate_and_encode(plantuml_text): |
| 23 | + """ |
| 24 | + zlib compress the plantuml text and encode it for the plantuml server. |
| 25 | +
|
| 26 | + Ref: https://plantuml.com/en/text-encoding |
| 27 | + """ |
| 28 | + plantuml_alphabet = ( |
| 29 | + string.digits + string.ascii_uppercase + string.ascii_lowercase + "-_" |
| 30 | + ) |
| 31 | + base64_alphabet = ( |
| 32 | + string.ascii_uppercase + string.ascii_lowercase + string.digits + "+/" |
| 33 | + ) |
| 34 | + b64_to_plantuml = bytes.maketrans( |
| 35 | + base64_alphabet.encode("utf-8"), plantuml_alphabet.encode("utf-8") |
| 36 | + ) |
| 37 | + zlibbed_str = compress(plantuml_text.encode("utf-8")) |
| 38 | + compressed_string = zlibbed_str[2:-4] |
| 39 | + return b64encode(compressed_string).translate(b64_to_plantuml).decode("utf-8") |
13 | 40 |
|
14 | 41 |
|
15 | 42 | class State:
|
@@ -248,4 +275,20 @@ def generate_plantuml(self) -> str:
|
248 | 275 | plant_uml.append(transition)
|
249 | 276 |
|
250 | 277 | plant_uml.append("@enduml")
|
251 |
| - return "\n".join(plant_uml) |
| 278 | + plant_uml_text = "\n".join(plant_uml) |
| 279 | + |
| 280 | + try: |
| 281 | + url = f"http://www.plantuml.com/plantuml/img/{deflate_and_encode(plant_uml_text)}" |
| 282 | + headers = {"User-Agent": "Mozilla/5.0"} |
| 283 | + request = Request(url, headers=headers) |
| 284 | + |
| 285 | + with urlopen(request) as response: |
| 286 | + content = response.read() |
| 287 | + |
| 288 | + plt.imshow(imread(BytesIO(content), format="png")) |
| 289 | + plt.axis("off") |
| 290 | + plt.show() |
| 291 | + except Exception as e: |
| 292 | + print(f"Error showing PlantUML: {e}") |
| 293 | + |
| 294 | + return plant_uml_text |
0 commit comments