create_images.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. """
  2. This module provides functionalities for creating and managing images using Bing's service.
  3. It includes functions for user login, session creation, image creation, and processing.
  4. """
  5. import asyncio
  6. import time
  7. import json
  8. import os
  9. from aiohttp import ClientSession
  10. from bs4 import BeautifulSoup
  11. from urllib.parse import quote
  12. from typing import Generator, List, Dict
  13. from ..create_images import CreateImagesProvider
  14. from ..helper import get_cookies, get_event_loop
  15. from ...webdriver import WebDriver, get_driver_cookies, get_browser
  16. from ...base_provider import ProviderType
  17. from ...image import format_images_markdown
  18. BING_URL = "https://www.bing.com"
  19. TIMEOUT_LOGIN = 1200
  20. TIMEOUT_IMAGE_CREATION = 300
  21. ERRORS = [
  22. "this prompt is being reviewed",
  23. "this prompt has been blocked",
  24. "we're working hard to offer image creator in more languages",
  25. "we can't create your images right now"
  26. ]
  27. BAD_IMAGES = [
  28. "https://r.bing.com/rp/in-2zU3AJUdkgFe7ZKv19yPBHVs.png",
  29. "https://r.bing.com/rp/TX9QuO3WzcCJz1uaaSwQAz39Kb0.jpg",
  30. ]
  31. def wait_for_login(driver: WebDriver, timeout: int = TIMEOUT_LOGIN) -> None:
  32. """
  33. Waits for the user to log in within a given timeout period.
  34. Args:
  35. driver (WebDriver): Webdriver for browser automation.
  36. timeout (int): Maximum waiting time in seconds.
  37. Raises:
  38. RuntimeError: If the login process exceeds the timeout.
  39. """
  40. driver.get(f"{BING_URL}/")
  41. start_time = time.time()
  42. while not driver.get_cookie("_U"):
  43. if time.time() - start_time > timeout:
  44. raise RuntimeError("Timeout error")
  45. time.sleep(0.5)
  46. def create_session(cookies: Dict[str, str]) -> ClientSession:
  47. """
  48. Creates a new client session with specified cookies and headers.
  49. Args:
  50. cookies (Dict[str, str]): Cookies to be used for the session.
  51. Returns:
  52. ClientSession: The created client session.
  53. """
  54. headers = {
  55. "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
  56. "accept-encoding": "gzip, deflate, br",
  57. "accept-language": "en-US,en;q=0.9,zh-CN;q=0.8,zh-TW;q=0.7,zh;q=0.6",
  58. "content-type": "application/x-www-form-urlencoded",
  59. "referrer-policy": "origin-when-cross-origin",
  60. "referrer": "https://www.bing.com/images/create/",
  61. "origin": "https://www.bing.com",
  62. "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36 Edg/111.0.1661.54",
  63. "sec-ch-ua": "\"Microsoft Edge\";v=\"111\", \"Not(A:Brand\";v=\"8\", \"Chromium\";v=\"111\"",
  64. "sec-ch-ua-mobile": "?0",
  65. "sec-fetch-dest": "document",
  66. "sec-fetch-mode": "navigate",
  67. "sec-fetch-site": "same-origin",
  68. "sec-fetch-user": "?1",
  69. "upgrade-insecure-requests": "1",
  70. }
  71. if cookies:
  72. headers["Cookie"] = "; ".join(f"{k}={v}" for k, v in cookies.items())
  73. return ClientSession(headers=headers)
  74. async def create_images(session: ClientSession, prompt: str, proxy: str = None, timeout: int = TIMEOUT_IMAGE_CREATION) -> List[str]:
  75. """
  76. Creates images based on a given prompt using Bing's service.
  77. Args:
  78. session (ClientSession): Active client session.
  79. prompt (str): Prompt to generate images.
  80. proxy (str, optional): Proxy configuration.
  81. timeout (int): Timeout for the request.
  82. Returns:
  83. List[str]: A list of URLs to the created images.
  84. Raises:
  85. RuntimeError: If image creation fails or times out.
  86. """
  87. url_encoded_prompt = quote(prompt)
  88. payload = f"q={url_encoded_prompt}&rt=4&FORM=GENCRE"
  89. url = f"{BING_URL}/images/create?q={url_encoded_prompt}&rt=4&FORM=GENCRE"
  90. async with session.post(url, allow_redirects=False, data=payload, timeout=timeout) as response:
  91. response.raise_for_status()
  92. text = (await response.text()).lower()
  93. for error in ERRORS:
  94. if error in text:
  95. raise RuntimeError(f"Create images failed: {error}")
  96. if response.status != 302:
  97. url = f"{BING_URL}/images/create?q={url_encoded_prompt}&rt=3&FORM=GENCRE"
  98. async with session.post(url, allow_redirects=False, proxy=proxy, timeout=timeout) as response:
  99. if response.status != 302:
  100. raise RuntimeError(f"Create images failed. Code: {response.status}")
  101. redirect_url = response.headers["Location"].replace("&nfy=1", "")
  102. redirect_url = f"{BING_URL}{redirect_url}"
  103. request_id = redirect_url.split("id=")[1]
  104. async with session.get(redirect_url) as response:
  105. response.raise_for_status()
  106. polling_url = f"{BING_URL}/images/create/async/results/{request_id}?q={url_encoded_prompt}"
  107. start_time = time.time()
  108. while True:
  109. if time.time() - start_time > timeout:
  110. raise RuntimeError(f"Timeout error after {timeout} sec")
  111. async with session.get(polling_url) as response:
  112. if response.status != 200:
  113. raise RuntimeError(f"Polling images faild. Code: {response.status}")
  114. text = await response.text()
  115. if not text:
  116. await asyncio.sleep(1)
  117. else:
  118. break
  119. error = None
  120. try:
  121. error = json.loads(text).get("errorMessage")
  122. except:
  123. pass
  124. if error == "Pending":
  125. raise RuntimeError("Prompt is been blocked")
  126. elif error:
  127. raise RuntimeError(error)
  128. return read_images(text)
  129. def read_images(html_content: str) -> List[str]:
  130. """
  131. Extracts image URLs from the HTML content.
  132. Args:
  133. html_content (str): HTML content containing image URLs.
  134. Returns:
  135. List[str]: A list of image URLs.
  136. """
  137. soup = BeautifulSoup(html_content, "html.parser")
  138. tags = soup.find_all("img", class_="mimg")
  139. images = [img["src"].split("?w=")[0] for img in tags]
  140. if any(im in BAD_IMAGES for im in images):
  141. raise RuntimeError("Bad images found")
  142. if not images:
  143. raise RuntimeError("No images found")
  144. return images
  145. async def create_images_markdown(cookies: Dict[str, str], prompt: str, proxy: str = None) -> str:
  146. """
  147. Creates markdown formatted string with images based on the prompt.
  148. Args:
  149. cookies (Dict[str, str]): Cookies to be used for the session.
  150. prompt (str): Prompt to generate images.
  151. proxy (str, optional): Proxy configuration.
  152. Returns:
  153. str: Markdown formatted string with images.
  154. """
  155. async with create_session(cookies) as session:
  156. images = await create_images(session, prompt, proxy)
  157. return format_images_markdown(images, prompt)
  158. def get_cookies_from_browser(proxy: str = None) -> Dict[str, str]:
  159. """
  160. Retrieves cookies from the browser using webdriver.
  161. Args:
  162. proxy (str, optional): Proxy configuration.
  163. Returns:
  164. Dict[str, str]: Retrieved cookies.
  165. """
  166. with get_browser(proxy=proxy) as driver:
  167. wait_for_login(driver)
  168. time.sleep(1)
  169. return get_driver_cookies(driver)
  170. class CreateImagesBing:
  171. """A class for creating images using Bing."""
  172. _cookies: Dict[str, str] = {}
  173. @classmethod
  174. def create_completion(cls, prompt: str, cookies: Dict[str, str] = None, proxy: str = None) -> Generator[str, None, None]:
  175. """
  176. Generator for creating imagecompletion based on a prompt.
  177. Args:
  178. prompt (str): Prompt to generate images.
  179. cookies (Dict[str, str], optional): Cookies for the session. If None, cookies are retrieved automatically.
  180. proxy (str, optional): Proxy configuration.
  181. Yields:
  182. Generator[str, None, None]: The final output as markdown formatted string with images.
  183. """
  184. loop = get_event_loop()
  185. cookies = cookies or cls._cookies or get_cookies(".bing.com")
  186. if "_U" not in cookies:
  187. login_url = os.environ.get("G4F_LOGIN_URL")
  188. if login_url:
  189. yield f"Please login: [Bing]({login_url})\n\n"
  190. cls._cookies = cookies = get_cookies_from_browser(proxy)
  191. yield loop.run_until_complete(create_images_markdown(cookies, prompt, proxy))
  192. @classmethod
  193. async def create_async(cls, prompt: str, cookies: Dict[str, str] = None, proxy: str = None) -> str:
  194. """
  195. Asynchronously creates a markdown formatted string with images based on the prompt.
  196. Args:
  197. prompt (str): Prompt to generate images.
  198. cookies (Dict[str, str], optional): Cookies for the session. If None, cookies are retrieved automatically.
  199. proxy (str, optional): Proxy configuration.
  200. Returns:
  201. str: Markdown formatted string with images.
  202. """
  203. cookies = cookies or cls._cookies or get_cookies(".bing.com")
  204. if "_U" not in cookies:
  205. cls._cookies = cookies = get_cookies_from_browser(proxy)
  206. return await create_images_markdown(cookies, prompt, proxy)
  207. def patch_provider(provider: ProviderType) -> CreateImagesProvider:
  208. """
  209. Patches a provider to include image creation capabilities.
  210. Args:
  211. provider (ProviderType): The provider to be patched.
  212. Returns:
  213. CreateImagesProvider: The patched provider with image creation capabilities.
  214. """
  215. return CreateImagesProvider(provider, CreateImagesBing.create_completion, CreateImagesBing.create_async)