from http import HTTPStatus
import dashscope
import os
from dashscope import ImageSynthesis

# 需要配置环境变量
os.environ["DASHSCOPE_API_KEY"] = "sk-"


def judge_image(url: str, text: str):
    print(f"正在对图片进行校验,url:{url}, text:{text}")
    messages = [
        {
            "role": "user",
            "content": [
                {
                    "image": url,
                },
                {"text": text},
            ],
        }
    ]
    response = dashscope.MultiModalConversation.call(
        model="qwen-vl-plus",
        api_key=os.environ["DASHSCOPE_API_KEY"],
        messages=messages,
    )
    print("识别结果:")
    if response.status_code == HTTPStatus.OK:
        print(response)
    else:
        print(response.code)  # 错误码
        print(response.message)  # 错误信息

    return response


def text_to_image(prompt: str):
    # prompt = "Mouse rides elephant"
    print(f"现在正在进行图片生成,prompt:{prompt}")
    rsp = ImageSynthesis.call(
        model=ImageSynthesis.Models.wanx_v1,
        prompt=prompt,
        n=1,
        size="1024*1024",
        api_key=os.environ["DASHSCOPE_API_KEY"],
    )
    if rsp.status_code == HTTPStatus.OK:
        print("图片生成结果:")
        print(rsp.output)
        print(rsp.usage)

        # save file to current directory
        # for result in rsp.output.results:
        #     file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
        #     with open(".images/%s" % file_name, "wb+") as f:
        #         f.write(requests.get(result.url).content)

        return rsp.output.results[0].url
    else:
        print(
            "Failed, status_code: %s, code: %s, message: %s"
            % (rsp.status_code, rsp.code, rsp.message)
        )


if __name__ == "__main__":
    # simple_multimodal_conversation_call()
    prompt = """
Cloned sheep Dolly is leaning against a ewe, showing a strong bond between them. Surrounding them is a lush green meadow filled with blooming trees and vibrant flowers, creating a peaceful and harmonious natural scene."""
    # draw("two sheep in the field")
    text_to_image(prompt)