BingCreateImages.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. from __future__ import annotations
  2. from ...cookies import get_cookies
  3. from ...image import ImageResponse
  4. from ...errors import MissingAuthError
  5. from ...typing import AsyncResult, Messages, Cookies
  6. from ..base_provider import AsyncGeneratorProvider, ProviderModelMixin
  7. from ..bing.create_images import create_images, create_session
  8. class BingCreateImages(AsyncGeneratorProvider, ProviderModelMixin):
  9. label = "Microsoft Designer in Bing"
  10. url = "https://www.bing.com/images/create"
  11. working = True
  12. needs_auth = True
  13. image_models = ["dall-e-3"]
  14. models = image_models
  15. def __init__(self, cookies: Cookies = None, proxy: str = None, api_key: str = None) -> None:
  16. if api_key is not None:
  17. if cookies is None:
  18. cookies = {}
  19. cookies["_U"] = api_key
  20. self.cookies = cookies
  21. self.proxy = proxy
  22. @classmethod
  23. async def create_async_generator(
  24. cls,
  25. model: str,
  26. messages: Messages,
  27. prompt: str = None,
  28. api_key: str = None,
  29. cookies: Cookies = None,
  30. proxy: str = None,
  31. **kwargs
  32. ) -> AsyncResult:
  33. session = BingCreateImages(cookies, proxy, api_key)
  34. yield await session.generate(messages[-1]["content"] if prompt is None else prompt)
  35. async def generate(self, prompt: str) -> ImageResponse:
  36. """
  37. Asynchronously creates a markdown formatted string with images based on the prompt.
  38. Args:
  39. prompt (str): Prompt to generate images.
  40. Returns:
  41. str: Markdown formatted string with images.
  42. """
  43. cookies = self.cookies or get_cookies(".bing.com", False)
  44. if cookies is None or "_U" not in cookies:
  45. raise MissingAuthError('Missing "_U" cookie')
  46. async with create_session(cookies, self.proxy) as session:
  47. images = await create_images(session, prompt)
  48. return ImageResponse(images, prompt, {"preview": "{image}?w=200&h=200"} if len(images) > 1 else {})