Skip to content

🌟 The Multi-Agent Framework: First AI Software Company, Towards Natural Language Programming

feat: merge geekan:dev

莘权 马dadd09bfb5ec
diff --cc metagpt/utils/common.py
index 27cc66948,d3a922c5f..efe49e3fb
--- a/metagpt/utils/common.py
+++ b/metagpt/utils/common.py
@@@ -22,9 -24,9 +24,10 @@@ import r
import sys
import traceback
import typing
+ from io import BytesIO
from pathlib import Path
- from typing import Any, List, Tuple, Union
+ from typing import Any, Callable, List, Tuple, Union
+from urllib.parse import quote, unquote
import aiofiles
import loguru
@@@ -693,58 -611,43 +729,100 @@@ def list_files(root: str | Path) -> Lis
return files
+def parse_json_code_block(markdown_text: str) -> List[str]:
+ json_blocks = re.findall(r"```json(.*?)```", markdown_text, re.DOTALL)
+ return [v.strip() for v in json_blocks]
+
+
+def remove_white_spaces(v: str) -> str:
+ """
+ Removes white spaces from the provided string, excluding spaces within quotes.
+
+ Args:
+ v (str): The input string containing white spaces.
+
+ Returns:
+ str: The input string with white spaces removed, excluding spaces within quotes.
+ """
+ return re.sub(r"(?<!['\"])\s|(?<=['\"])\s", "", v)
+
+
+async def aread_bin(filename: str | Path) -> bytes:
+ """Read binary file asynchronously.
+
+ Args:
+ filename (Union[str, Path]): The name or path of the file to be read.
+
+ Returns:
+ bytes: The content of the file as bytes.
+
+ Example:
+ >>> content = await aread_bin('example.txt')
+ b'This is the content of the file.'
+
+ >>> content = await aread_bin(Path('example.txt'))
+ b'This is the content of the file.'
+ """
+ async with aiofiles.open(str(filename), mode="rb") as reader:
+ content = await reader.read()
+ return content
+
+
+async def awrite_bin(filename: str | Path, data: bytes):
+ """Write binary file asynchronously.
+
+ Args:
+ filename (Union[str, Path]): The name or path of the file to be written.
+ data (bytes): The binary data to be written to the file.
+
+ Example:
+ >>> await awrite_bin('output.bin', b'This is binary data.')
+
+ >>> await awrite_bin(Path('output.bin'), b'Another set of binary data.')
+ """
+ pathname = Path(filename)
+ pathname.parent.mkdir(parents=True, exist_ok=True)
+ async with aiofiles.open(str(pathname), mode="wb") as writer:
+ await writer.write(data)
++
++
+ def is_coroutine_func(func: Callable) -> bool:
+ return inspect.iscoroutinefunction(func)
+
+
+ def load_mc_skills_code(skill_names: list[str] = None, skills_dir: Path = None) -> list[str]:
+ """load mincraft skill from js files"""
+ if not skills_dir:
+ skills_dir = Path(__file__).parent.absolute()
+ if skill_names is None:
+ skill_names = [skill[:-3] for skill in os.listdir(f"{skills_dir}") if skill.endswith(".js")]
+ skills = [skills_dir.joinpath(f"{skill_name}.js").read_text() for skill_name in skill_names]
+ return skills
+
+
+ def encode_image(image_path_or_pil: Union[Path, Image], encoding: str = "utf-8") -> str:
+ """encode image from file or PIL.Image into base64"""
+ if isinstance(image_path_or_pil, Image.Image):
+ buffer = BytesIO()
+ image_path_or_pil.save(buffer, format="JPEG")
+ bytes_data = buffer.getvalue()
+ else:
+ if not image_path_or_pil.exists():
+ raise FileNotFoundError(f"{image_path_or_pil} not exists")
+ with open(str(image_path_or_pil), "rb") as image_file:
+ bytes_data = image_file.read()
+ return base64.b64encode(bytes_data).decode(encoding)
+
+
+ def decode_image(img_url_or_b64: str) -> Image:
+ """decode image from url or base64 into PIL.Image"""
+ if img_url_or_b64.startswith("http"):
+ # image http(s) url
+ resp = requests.get(img_url_or_b64)
+ img = Image.open(BytesIO(resp.content))
+ else:
+ # image b64_json
+ b64_data = re.sub("^data:image/.+;base64,", "", img_url_or_b64)
+ img_data = BytesIO(base64.b64decode(b64_data))
+ img = Image.open(img_data)
+ return img