1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| import json import requests
import numpy as np
from agentlego.types import Annotated, ImageIO, Info from agentlego.utils import require from .base import BaseTool
class MagicMakerImageGeneration(BaseTool):
default_desc = ('This tool can call the api of magicmaker to ' 'generate an image according to the given keywords.')
styles_option = [ 'dongman', 'guofeng', 'xieshi', 'youhua', 'manghe', ] aspect_ratio_options = [ '16:9', '4:3', '3:2', '1:1', '2:3', '3:4', '9:16' ]
@require('opencv-python') def __init__(self, style='guofeng', aspect_ratio='4:3'): super().__init__() if style in self.styles_option: self.style = style else: raise ValueError(f'The style must be one of {self.styles_option}')
if aspect_ratio in self.aspect_ratio_options: self.aspect_ratio = aspect_ratio else: raise ValueError(f'The aspect ratio must be one of {aspect_ratio}')
def apply(self, keywords: Annotated[str, Info('A series of Chinese keywords separated by comma.')] ) -> ImageIO: import cv2 response = requests.post( url='https://magicmaker.openxlab.org.cn/gw/edit-anything/api/v1/bff/sd/generate', data=json.dumps({ "official": True, "prompt": keywords, "style": self.style, "poseT": False, "aspectRatio": self.aspect_ratio }), headers={'content-type': 'application/json'} ) image_url = response.json()['data']['imgUrl'] image_response = requests.get(image_url) image = cv2.cvtColor(cv2.imdecode(np.frombuffer(image_response.content, np.uint8), cv2.IMREAD_COLOR),cv2.COLOR_BGR2RGB) return ImageIO(image)
|