Total Complexity | 10 |
Total Lines | 75 |
Duplicated Lines | 0 % |
Changes | 0 |
1 | # Copyright Pincer 2021-Present |
||
2 | # Full MIT License can be found in `LICENSE` at the project root. |
||
3 | |||
4 | import aiohttp |
||
5 | import argparse |
||
6 | import asyncio |
||
7 | import base64 |
||
8 | import glob |
||
9 | import io |
||
10 | import os |
||
11 | from PIL import Image |
||
12 | |||
13 | |||
14 | async def download_img(base64_string): |
||
15 | async with aiohttp.ClientSession() as session: |
||
16 | async with session.get( |
||
17 | 'https://mermaid.ink/img/' + base64_string.decode("ascii") |
||
18 | ) as resp: |
||
19 | return Image.open(io.BytesIO(await resp.content.read())) |
||
20 | |||
21 | |||
22 | async def download_file(file): |
||
23 | with open(file) as f: |
||
24 | contents = f.read() |
||
25 | graphbytes = contents.encode("ascii") |
||
26 | base64_bytes = base64.b64encode(graphbytes) |
||
27 | image = await download_img(base64_bytes) |
||
28 | image.save(os.path.splitext(file)[0] + ".png") |
||
29 | |||
30 | |||
31 | async def download_all(directory): |
||
32 | if not directory: |
||
33 | directory = "" |
||
34 | |||
35 | await asyncio.gather(*( |
||
36 | download_file(file) |
||
|
|||
37 | for file in glob.glob(directory + "*.mmd") |
||
38 | )) |
||
39 | |||
40 | |||
41 | def main(): |
||
42 | parser = argparse.ArgumentParser( |
||
43 | description='Download rendered mermaid files.' |
||
44 | ) |
||
45 | parser.add_argument( |
||
46 | '--file', |
||
47 | type=str, |
||
48 | nargs='?', |
||
49 | help='A file to download. If not specified all files are downloaded.', |
||
50 | default=None |
||
51 | ) |
||
52 | parser.add_argument( |
||
53 | '--dir', |
||
54 | type=str, |
||
55 | nargs='?', |
||
56 | help='Directory to search. Does not work with --file.', |
||
57 | default=None |
||
58 | ) |
||
59 | |||
60 | args = parser.parse_args() |
||
61 | |||
62 | if "help" in args: |
||
63 | print(args) |
||
64 | return |
||
65 | |||
66 | if args.file: |
||
67 | asyncio.run(download_file(args.file)) |
||
68 | return |
||
69 | |||
70 | asyncio.run(download_all(args.dir)) |
||
71 | |||
72 | |||
73 | if __name__ == "__main__": |
||
74 | main() |
||
75 |