img.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. from http import HTTPStatus
  2. import dashscope
  3. import os
  4. from dashscope import ImageSynthesis
  5. # 需要配置环境变量
  6. os.environ["DASHSCOPE_API_KEY"] = ""
  7. def judge_image(url: str, text: str):
  8. print(f"正在对图片进行校验,url:{url}, text:{text}")
  9. messages = [
  10. {
  11. "role": "user",
  12. "content": [
  13. {
  14. "image": url,
  15. },
  16. {"text": text},
  17. ],
  18. }
  19. ]
  20. response = dashscope.MultiModalConversation.call(
  21. model="qwen-vl-plus",
  22. api_key=os.environ["DASHSCOPE_API_KEY"],
  23. messages=messages,
  24. )
  25. print("识别结果:")
  26. if response.status_code == HTTPStatus.OK:
  27. print(response)
  28. else:
  29. print(response.code) # 错误码
  30. print(response.message) # 错误信息
  31. return response
  32. def text_to_image(prompt: str):
  33. # prompt = "Mouse rides elephant"
  34. print(f"现在正在进行图片生成,prompt:{prompt}")
  35. rsp = ImageSynthesis.call(
  36. model=ImageSynthesis.Models.wanx_v1,
  37. prompt=prompt,
  38. n=1,
  39. size="1024*1024",
  40. api_key=os.environ["DASHSCOPE_API_KEY"],
  41. )
  42. if rsp.status_code == HTTPStatus.OK:
  43. print("图片生成结果:")
  44. print(rsp.output)
  45. print(rsp.usage)
  46. # save file to current directory
  47. # for result in rsp.output.results:
  48. # file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
  49. # with open(".images/%s" % file_name, "wb+") as f:
  50. # f.write(requests.get(result.url).content)
  51. return rsp.output.results[0].url
  52. else:
  53. print(
  54. "Failed, status_code: %s, code: %s, message: %s"
  55. % (rsp.status_code, rsp.code, rsp.message)
  56. )
  57. if __name__ == "__main__":
  58. # simple_multimodal_conversation_call()
  59. prompt = """
  60. 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."""
  61. # draw("two sheep in the field")
  62. text_to_image(prompt)