MetaGPT
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3"""
4@Time : 2023/9/4 16:12
5@Author : alitrack
6@File : mermaid.py
7"""
8import base64
9
10from aiohttp import ClientError, ClientSession
11
12from metagpt.logs import logger
13
14
15async def mermaid_to_file(mermaid_code, output_file_without_suffix):
16"""suffix: png/svg
17:param mermaid_code: mermaid code
18:param output_file_without_suffix: output filename without suffix
19:return: 0 if succeed, -1 if failed
20"""
21encoded_string = base64.b64encode(mermaid_code.encode()).decode()
22
23for suffix in ["svg", "png"]:
24output_file = f"{output_file_without_suffix}.{suffix}"
25path_type = "svg" if suffix == "svg" else "img"
26url = f"https://mermaid.ink/{path_type}/{encoded_string}"
27async with ClientSession() as session:
28try:
29async with session.get(url) as response:
30if response.status == 200:
31text = await response.content.read()
32with open(output_file, "wb") as f:
33f.write(text)
34logger.info(f"Generating {output_file}..")
35else:
36logger.error(f"Failed to generate {output_file}")
37return -1
38except ClientError as e:
39logger.error(f"network error: {e}")
40return -1
41return 0
42