BingCreateImages.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. from __future__ import annotations
  2. import asyncio
  3. import os
  4. from typing import Generator
  5. from ..cookies import get_cookies
  6. from ..image import ImageResponse
  7. from ..errors import MissingRequirementsError, MissingAuthError
  8. from .bing.create_images import create_images, create_session, get_cookies_from_browser
  9. class BingCreateImages:
  10. """A class for creating images using Bing."""
  11. def __init__(self, cookies: dict[str, str] = {}, proxy: str = None) -> None:
  12. self.cookies = cookies
  13. self.proxy = proxy
  14. def create(self, prompt: str) -> Generator[ImageResponse, None, None]:
  15. """
  16. Generator for creating imagecompletion based on a prompt.
  17. Args:
  18. prompt (str): Prompt to generate images.
  19. Yields:
  20. Generator[str, None, None]: The final output as markdown formatted string with images.
  21. """
  22. cookies = self.cookies or get_cookies(".bing.com", False)
  23. if "_U" not in cookies:
  24. login_url = os.environ.get("G4F_LOGIN_URL")
  25. if login_url:
  26. yield f"Please login: [Bing]({login_url})\n\n"
  27. try:
  28. self.cookies = get_cookies_from_browser(self.proxy)
  29. except MissingRequirementsError as e:
  30. raise MissingAuthError(f'Missing "_U" cookie. {e}')
  31. yield asyncio.run(self.create_async(prompt))
  32. async def create_async(self, prompt: str) -> ImageResponse:
  33. """
  34. Asynchronously creates a markdown formatted string with images based on the prompt.
  35. Args:
  36. prompt (str): Prompt to generate images.
  37. Returns:
  38. str: Markdown formatted string with images.
  39. """
  40. cookies = self.cookies or get_cookies(".bing.com", False)
  41. if "_U" not in cookies:
  42. raise MissingAuthError('Missing "_U" cookie')
  43. proxy = self.proxy or os.environ.get("G4F_PROXY")
  44. async with create_session(cookies, proxy) as session:
  45. images = await create_images(session, prompt, proxy)
  46. return ImageResponse(images, prompt, {"preview": "{image}?w=200&h=200"} if len(images) > 1 else {})