Gemini.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. from __future__ import annotations
  2. import os
  3. import json
  4. import random
  5. import re
  6. import base64
  7. import asyncio
  8. from aiohttp import ClientSession, BaseConnector
  9. try:
  10. import nodriver
  11. has_nodriver = True
  12. except ImportError:
  13. has_nodriver = False
  14. from ... import debug
  15. from ...typing import Messages, Cookies, ImagesType, AsyncResult, AsyncIterator
  16. from ..base_provider import AsyncGeneratorProvider, ProviderModelMixin, BaseConversation, SynthesizeData
  17. from ..helper import format_prompt, get_cookies
  18. from ...requests.raise_for_status import raise_for_status
  19. from ...requests.aiohttp import get_connector
  20. from ...requests import get_nodriver
  21. from ...errors import MissingAuthError
  22. from ...image import ImageResponse, to_bytes
  23. from ... import debug
  24. REQUEST_HEADERS = {
  25. "authority": "gemini.google.com",
  26. "origin": "https://gemini.google.com",
  27. "referer": "https://gemini.google.com/",
  28. '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',
  29. 'x-same-domain': '1',
  30. }
  31. REQUEST_BL_PARAM = "boq_assistant-bard-web-server_20240519.16_p0"
  32. REQUEST_URL = "https://gemini.google.com/_/BardChatUi/data/assistant.lamda.BardFrontendService/StreamGenerate"
  33. UPLOAD_IMAGE_URL = "https://content-push.googleapis.com/upload/"
  34. UPLOAD_IMAGE_HEADERS = {
  35. "authority": "content-push.googleapis.com",
  36. "accept": "*/*",
  37. "accept-language": "en-US,en;q=0.7",
  38. "authorization": "Basic c2F2ZXM6cyNMdGhlNmxzd2F2b0RsN3J1d1U=",
  39. "content-type": "application/x-www-form-urlencoded;charset=UTF-8",
  40. "origin": "https://gemini.google.com",
  41. "push-id": "feeds/mcudyrk2a4khkz",
  42. "referer": "https://gemini.google.com/",
  43. "x-goog-upload-command": "start",
  44. "x-goog-upload-header-content-length": "",
  45. "x-goog-upload-protocol": "resumable",
  46. "x-tenant-id": "bard-storage",
  47. }
  48. class Gemini(AsyncGeneratorProvider, ProviderModelMixin):
  49. label = "Google Gemini"
  50. url = "https://gemini.google.com"
  51. needs_auth = True
  52. working = True
  53. default_model = 'gemini'
  54. image_models = ["gemini"]
  55. default_vision_model = "gemini"
  56. models = ["gemini", "gemini-1.5-flash", "gemini-1.5-pro"]
  57. model_aliases = {
  58. "gemini-flash": "gemini-1.5-flash",
  59. "gemini-pro": "gemini-1.5-pro",
  60. }
  61. synthesize_content_type = "audio/vnd.wav"
  62. _cookies: Cookies = None
  63. _snlm0e: str = None
  64. _sid: str = None
  65. @classmethod
  66. async def nodriver_login(cls, proxy: str = None) -> AsyncIterator[str]:
  67. if not has_nodriver:
  68. if debug.logging:
  69. print("Skip nodriver login in Gemini provider")
  70. return
  71. browser = await get_nodriver(proxy=proxy, user_data_dir="gemini")
  72. login_url = os.environ.get("G4F_LOGIN_URL")
  73. if login_url:
  74. yield f"Please login: [Google Gemini]({login_url})\n\n"
  75. page = await browser.get(f"{cls.url}/app")
  76. await page.select("div.ql-editor.textarea", 240)
  77. cookies = {}
  78. for c in await page.send(nodriver.cdp.network.get_cookies([cls.url])):
  79. cookies[c.name] = c.value
  80. await page.close()
  81. cls._cookies = cookies
  82. @classmethod
  83. async def create_async_generator(
  84. cls,
  85. model: str,
  86. messages: Messages,
  87. proxy: str = None,
  88. cookies: Cookies = None,
  89. connector: BaseConnector = None,
  90. images: ImagesType = None,
  91. return_conversation: bool = False,
  92. conversation: Conversation = None,
  93. language: str = "en",
  94. **kwargs
  95. ) -> AsyncResult:
  96. prompt = format_prompt(messages) if conversation is None else messages[-1]["content"]
  97. cls._cookies = cookies or cls._cookies or get_cookies(".google.com", False, True)
  98. base_connector = get_connector(connector, proxy)
  99. async with ClientSession(
  100. headers=REQUEST_HEADERS,
  101. connector=base_connector
  102. ) as session:
  103. if not cls._snlm0e:
  104. await cls.fetch_snlm0e(session, cls._cookies) if cls._cookies else None
  105. if not cls._snlm0e:
  106. try:
  107. async for chunk in cls.nodriver_login(proxy):
  108. yield chunk
  109. except Exception as e:
  110. raise MissingAuthError('Missing or invalid "__Secure-1PSID" cookie', e)
  111. if not cls._snlm0e:
  112. if cls._cookies is None or "__Secure-1PSID" not in cls._cookies:
  113. raise MissingAuthError('Missing "__Secure-1PSID" cookie')
  114. await cls.fetch_snlm0e(session, cls._cookies)
  115. if not cls._snlm0e:
  116. raise RuntimeError("Invalid cookies. SNlM0e not found")
  117. yield SynthesizeData(cls.__name__, {"text": messages[-1]["content"]})
  118. images = await cls.upload_images(base_connector, images) if images else None
  119. async with ClientSession(
  120. cookies=cls._cookies,
  121. headers=REQUEST_HEADERS,
  122. connector=base_connector,
  123. ) as client:
  124. params = {
  125. 'bl': REQUEST_BL_PARAM,
  126. 'hl': language,
  127. '_reqid': random.randint(1111, 9999),
  128. 'rt': 'c',
  129. "f.sid": cls._sid,
  130. }
  131. data = {
  132. 'at': cls._snlm0e,
  133. 'f.req': json.dumps([None, json.dumps(cls.build_request(
  134. prompt,
  135. language=language,
  136. conversation=conversation,
  137. images=images
  138. ))])
  139. }
  140. async with client.post(
  141. REQUEST_URL,
  142. data=data,
  143. params=params,
  144. ) as response:
  145. await raise_for_status(response)
  146. image_prompt = response_part = None
  147. last_content = ""
  148. async for line in response.content:
  149. try:
  150. try:
  151. line = json.loads(line)
  152. except ValueError:
  153. continue
  154. if not isinstance(line, list):
  155. continue
  156. if len(line[0]) < 3 or not line[0][2]:
  157. continue
  158. response_part = json.loads(line[0][2])
  159. if not response_part[4]:
  160. continue
  161. if return_conversation:
  162. yield Conversation(response_part[1][0], response_part[1][1], response_part[4][0][0])
  163. content = response_part[4][0][1][0]
  164. except (ValueError, KeyError, TypeError, IndexError) as e:
  165. debug.log(f"{cls.__name__}:{e.__class__.__name__}:{e}")
  166. continue
  167. match = re.search(r'\[Imagen of (.*?)\]', content)
  168. if match:
  169. image_prompt = match.group(1)
  170. content = content.replace(match.group(0), '')
  171. pattern = r"http://googleusercontent.com/image_generation_content/\d+"
  172. content = re.sub(pattern, "", content)
  173. if last_content and content.startswith(last_content):
  174. yield content[len(last_content):]
  175. else:
  176. yield content
  177. last_content = content
  178. if image_prompt:
  179. try:
  180. images = [image[0][3][3] for image in response_part[4][0][12][7][0]]
  181. image_prompt = image_prompt.replace("a fake image", "")
  182. yield ImageResponse(images, image_prompt, {"cookies": cls._cookies})
  183. except (TypeError, IndexError, KeyError):
  184. pass
  185. @classmethod
  186. async def synthesize(cls, params: dict, proxy: str = None) -> AsyncIterator[bytes]:
  187. if "text" not in params:
  188. raise ValueError("Missing parameter text")
  189. async with ClientSession(
  190. cookies=cls._cookies,
  191. headers=REQUEST_HEADERS,
  192. connector=get_connector(proxy=proxy),
  193. ) as session:
  194. if not cls._snlm0e:
  195. await cls.fetch_snlm0e(session, cls._cookies) if cls._cookies else None
  196. inner_data = json.dumps([None, params["text"], "de-DE", None, 2])
  197. async with session.post(
  198. "https://gemini.google.com/_/BardChatUi/data/batchexecute",
  199. data={
  200. "f.req": json.dumps([[["XqA3Ic", inner_data, None, "generic"]]]),
  201. "at": cls._snlm0e,
  202. },
  203. params={
  204. "rpcids": "XqA3Ic",
  205. "source-path": "/app/2704fb4aafcca926",
  206. "bl": "boq_assistant-bard-web-server_20241119.00_p1",
  207. "f.sid": "" if cls._sid is None else cls._sid,
  208. "hl": "de",
  209. "_reqid": random.randint(1111, 9999),
  210. "rt": "c"
  211. },
  212. ) as response:
  213. await raise_for_status(response)
  214. iter_base64_response = iter_filter_base64(response.content.iter_chunked(1024))
  215. async for chunk in iter_base64_decode(iter_base64_response):
  216. yield chunk
  217. def build_request(
  218. prompt: str,
  219. language: str,
  220. conversation: Conversation = None,
  221. images: list[list[str, str]] = None,
  222. tools: list[list[str]] = []
  223. ) -> list:
  224. image_list = [[[image_url, 1], image_name] for image_url, image_name in images] if images else []
  225. return [
  226. [prompt, 0, None, image_list, None, None, 0],
  227. [language],
  228. [
  229. None if conversation is None else conversation.conversation_id,
  230. None if conversation is None else conversation.response_id,
  231. None if conversation is None else conversation.choice_id,
  232. None,
  233. None,
  234. []
  235. ],
  236. None,
  237. None,
  238. None,
  239. [1],
  240. 0,
  241. [],
  242. tools,
  243. 1,
  244. 0,
  245. ]
  246. async def upload_images(connector: BaseConnector, images: ImagesType) -> list:
  247. async def upload_image(image: bytes, image_name: str = None):
  248. async with ClientSession(
  249. headers=UPLOAD_IMAGE_HEADERS,
  250. connector=connector
  251. ) as session:
  252. image = to_bytes(image)
  253. async with session.options(UPLOAD_IMAGE_URL) as response:
  254. await raise_for_status(response)
  255. headers = {
  256. "size": str(len(image)),
  257. "x-goog-upload-command": "start"
  258. }
  259. data = f"File name: {image_name}" if image_name else None
  260. async with session.post(
  261. UPLOAD_IMAGE_URL, headers=headers, data=data
  262. ) as response:
  263. await raise_for_status(response)
  264. upload_url = response.headers["X-Goog-Upload-Url"]
  265. async with session.options(upload_url, headers=headers) as response:
  266. await raise_for_status(response)
  267. headers["x-goog-upload-command"] = "upload, finalize"
  268. headers["X-Goog-Upload-Offset"] = "0"
  269. async with session.post(
  270. upload_url, headers=headers, data=image
  271. ) as response:
  272. await raise_for_status(response)
  273. return [await response.text(), image_name]
  274. return await asyncio.gather(*[upload_image(image, image_name) for image, image_name in images])
  275. @classmethod
  276. async def fetch_snlm0e(cls, session: ClientSession, cookies: Cookies):
  277. async with session.get(cls.url, cookies=cookies) as response:
  278. await raise_for_status(response)
  279. response_text = await response.text()
  280. match = re.search(r'SNlM0e\":\"(.*?)\"', response_text)
  281. if match:
  282. cls._snlm0e = match.group(1)
  283. sid_match = re.search(r'"FdrFJe":"([\d-]+)"', response_text)
  284. if sid_match:
  285. cls._sid = sid_match.group(1)
  286. class Conversation(BaseConversation):
  287. def __init__(self,
  288. conversation_id: str = "",
  289. response_id: str = "",
  290. choice_id: str = ""
  291. ) -> None:
  292. self.conversation_id = conversation_id
  293. self.response_id = response_id
  294. self.choice_id = choice_id
  295. async def iter_filter_base64(response_iter: AsyncIterator[bytes]) -> AsyncIterator[bytes]:
  296. search_for = b'[["wrb.fr","XqA3Ic","[\\"'
  297. end_with = b'\\'
  298. is_started = False
  299. async for chunk in response_iter:
  300. if is_started:
  301. if end_with in chunk:
  302. yield chunk.split(end_with, 1).pop(0)
  303. break
  304. else:
  305. yield chunk
  306. elif search_for in chunk:
  307. is_started = True
  308. yield chunk.split(search_for, 1).pop()
  309. else:
  310. raise RuntimeError(f"Response: {chunk}")
  311. async def iter_base64_decode(response_iter: AsyncIterator[bytes]) -> AsyncIterator[bytes]:
  312. buffer = b""
  313. async for chunk in response_iter:
  314. chunk = buffer + chunk
  315. rest = len(chunk) % 4
  316. buffer = chunk[-rest:]
  317. yield base64.b64decode(chunk[:-rest])