You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

open_ai_image.py 1.7KB

1 yıl önce
1 yıl önce
1 yıl önce
1 yıl önce
1 yıl önce
1 yıl önce
1 yıl önce
1 yıl önce
1 yıl önce
1 yıl önce
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import time
  2. import openai
  3. import openai.error
  4. from common.log import logger
  5. from common.token_bucket import TokenBucket
  6. from config import conf
  7. # OPENAI提供的画图接口
  8. class OpenAIImage(object):
  9. def __init__(self):
  10. openai.api_key = conf().get("open_ai_api_key")
  11. if conf().get("rate_limit_dalle"):
  12. self.tb4dalle = TokenBucket(conf().get("rate_limit_dalle", 50))
  13. def create_img(self, query, retry_count=0):
  14. try:
  15. if conf().get("rate_limit_dalle") and not self.tb4dalle.get_token():
  16. return False, "请求太快了,请休息一下再问我吧"
  17. logger.info("[OPEN_AI] image_query={}".format(query))
  18. response = openai.Image.create(
  19. prompt=query, # 图片描述
  20. n=1, # 每次生成图片的数量
  21. size=conf().get(
  22. "image_create_size", "256x256"
  23. ), # 图片大小,可选有 256x256, 512x512, 1024x1024
  24. )
  25. image_url = response["data"][0]["url"]
  26. logger.info("[OPEN_AI] image_url={}".format(image_url))
  27. return True, image_url
  28. except openai.error.RateLimitError as e:
  29. logger.warn(e)
  30. if retry_count < 1:
  31. time.sleep(5)
  32. logger.warn(
  33. "[OPEN_AI] ImgCreate RateLimit exceed, 第{}次重试".format(
  34. retry_count + 1
  35. )
  36. )
  37. return self.create_img(query, retry_count + 1)
  38. else:
  39. return False, "提问太快啦,请休息一下再问我吧"
  40. except Exception as e:
  41. logger.exception(e)
  42. return False, str(e)