Created
July 27, 2023 20:21
-
-
Save maintainer64/99106a94f8acb8bd6e88162ecb116f79 to your computer and use it in GitHub Desktop.
uml-code, uml-export, uml_converter.py, converter markdown PlantUML extentions to png images
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import string | |
import requests | |
import zlib | |
import base64 | |
import pathlib | |
maketrans = bytes.maketrans | |
BEFORE = "scale 4000 width" | |
plantuml_alphabet = string.digits + string.ascii_uppercase + string.ascii_lowercase + '-_' | |
base64_alphabet = string.ascii_uppercase + string.ascii_lowercase + string.digits + '+/' | |
b64_to_plantuml = maketrans(base64_alphabet.encode('utf-8'), plantuml_alphabet.encode('utf-8')) | |
plantuml_to_b64 = maketrans(plantuml_alphabet.encode('utf-8'), base64_alphabet.encode('utf-8')) | |
def generate_url_by_params(type_: str, id_: str): | |
return f"https://www.planttext.com/api/plantuml/{type_}/{id_}" | |
def get_uml_content(content: str): | |
HEAD_CONTENT = '```plantuml' | |
END_CONTENT = '```' | |
START_CONTENT = '@startuml' | |
return content.replace(f"{HEAD_CONTENT}\n", "").replace(HEAD_CONTENT, "").replace(f"\n{END_CONTENT}", "").replace( | |
END_CONTENT, "").replace( | |
START_CONTENT, START_CONTENT + '\n' + BEFORE | |
) | |
def get_file_contents(): | |
currentDirectory = pathlib.Path('./uml-code') | |
for currentFile in currentDirectory.iterdir(): | |
with open(currentFile, "r") as fin: | |
yield currentFile.name.replace(".md", ""), get_uml_content(fin.read()) | |
def upload_file_content(url_save: str, filename: str): | |
r = requests.get(url_save) | |
r.raise_for_status() | |
with open(f'./uml-export/{filename}', 'wb') as f: | |
f.write(r.content) | |
def plantuml_encode(plantuml_text): | |
"""zlib compress the plantuml text and encode it for the plantuml server""" | |
zlibbed_str = zlib.compress(plantuml_text.encode('utf-8')) | |
compressed_string = zlibbed_str[2:-4] | |
return base64.b64encode(compressed_string).translate(b64_to_plantuml).decode('utf-8') | |
def plantuml_decode(plantuml_url): | |
"""decode plantuml encoded url back to plantuml text""" | |
data = base64.b64decode(plantuml_url.translate(plantuml_to_b64).encode("utf-8")) | |
dec = zlib.decompressobj() # without check the crc. | |
header = b'x\x9c' | |
return dec.decompress(header + data).decode("utf-8") | |
if __name__ == "__main__": | |
for filename, content_file in get_file_contents(): | |
url_string = plantuml_encode(content_file) | |
upload_file_content( | |
url_save=generate_url_by_params("png", url_string), | |
filename=f"{filename}.png" | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment