Skip to content
This repository was archived by the owner on Jun 12, 2024. It is now read-only.

Commit e138cb3

Browse files
committed
refactor: func order
1 parent 1b7c492 commit e138cb3

File tree

1 file changed

+126
-126
lines changed

1 file changed

+126
-126
lines changed

gemini/core.py

Lines changed: 126 additions & 126 deletions
Original file line numberDiff line numberDiff line change
@@ -95,28 +95,6 @@ def _initialize_session(
9595

9696
return session
9797

98-
def check_session_cookies(self) -> None:
99-
"""
100-
Prints the session's cookies. Indicates if the session is uninitialized.
101-
"""
102-
if self.session:
103-
cookies = self.session.cookies.get_dict()
104-
cookies_str = "\n".join(f"{key}: {value}" for key, value in cookies.items())
105-
print(f"Session Cookies:\n{cookies_str}")
106-
else:
107-
print("Session not initialized.")
108-
109-
def check_session_headers(self) -> None:
110-
"""
111-
Prints the session's headers. Indicates if the session is uninitialized.
112-
"""
113-
if self.session:
114-
headers = self.session.headers
115-
headers_str = "\n".join(f"{key}: {value}" for key, value in headers.items())
116-
print(f"Session Headers:\n{headers_str}")
117-
else:
118-
print("Session not initialized.")
119-
12098
def _load_cookies_from_file(self, file_path: str) -> None:
12199
"""Loads cookies from a file and updates the session."""
122100
try:
@@ -134,75 +112,6 @@ def _load_cookies_from_file(self, file_path: str) -> None:
134112
except Exception as e:
135113
print(f"Error loading cookie file: {e}")
136114

137-
def _set_cookies_automatically(self) -> None:
138-
"""
139-
Updates the instance's cookies attribute with Gemini API tokens, either from environment variables or by extracting them from the browser, based on the auto_cookies flag.
140-
"""
141-
if len(getattr(self, "cookies", {})) > 5:
142-
return
143-
144-
if self.auto_cookies:
145-
try:
146-
self._update_cookies_from_browser()
147-
if not self.cookies:
148-
raise ValueError("No cookies were loaded from the browser.")
149-
except Exception as e:
150-
raise Exception("Failed to extract cookies from browser.") from e
151-
else:
152-
print(
153-
"Cookie loading issue, try setting auto_cookies to True. Restart browser, log out, log in for Gemini Web UI to work. Keep a single browser open."
154-
)
155-
try:
156-
self.auto_cookies = True
157-
self._update_cookies_from_browser()
158-
if not self.cookies:
159-
raise ValueError("No cookies were loaded from the browser.")
160-
except Exception as e:
161-
print(f"Automatic cookie retrieval failed: {e}")
162-
163-
if not self.cookies:
164-
raise Exception(
165-
"Gemini cookies must be provided through environment variables or extracted from the browser with auto_cookies enabled."
166-
)
167-
168-
def _update_cookies_from_browser(self) -> dict:
169-
"""
170-
Attempts to extract specific Gemini cookies from the cookies stored by web browsers on the current system.
171-
172-
This method iterates over a predefined list of supported browsers, attempting to retrieve cookies that match a specific domain (e.g., ".google.com"). If the required cookies are found, they are added to the instance's cookie store. The process supports multiple modern web browsers across different operating systems.
173-
174-
The method updates the instance's `cookies` attribute with any found cookies that match the specified criteria.
175-
176-
Raises:
177-
ValueError: If no supported browser is found with the required cookies, or if an essential cookie is missing after attempting retrieval from all supported browsers.
178-
"""
179-
180-
for browser_fn in SUPPORTED_BROWSERS:
181-
try:
182-
print(
183-
f"Trying to automatically retrieve cookies from {browser_fn} using the browser_cookie3 package."
184-
)
185-
cj = browser_fn(domain_name=".google.com")
186-
found_cookies = {cookie.name: cookie.value for cookie in cj}
187-
if len(found_cookies) >= 5:
188-
print(
189-
f"Successfully retrieved cookies from {browser_fn}.\n{found_cookies}"
190-
)
191-
self.cookies = found_cookies
192-
break
193-
else:
194-
print(
195-
f"Automatically configure cookies with detected ones but found only {len(found_cookies)} cookies.\n{found_cookies}"
196-
)
197-
except Exception as e:
198-
print(e)
199-
continue
200-
201-
if not self.cookies:
202-
raise ValueError(
203-
"Failed to get cookies. Set 'cookies' argument or 'auto_cookies' as True."
204-
)
205-
206115
def _set_sid_and_nonce(self):
207116
"""
208117
Retrieves the session ID (SID) and a SNlM0e nonce value from the application page.
@@ -228,41 +137,6 @@ def _set_sid_and_nonce(self):
228137
except Exception as e:
229138
raise RuntimeError(f"An unexpected error occurred: {e}")
230139

231-
# def _set_sid_and_nonce(self) -> Tuple[str, str]:
232-
# """
233-
# Retrieves the session ID (SID) and a SNlM0e nonce value from the application page.
234-
# """
235-
# url = f"{HOST}/app"
236-
# try:
237-
# response = requests.get(
238-
# url, cookies=self.cookies
239-
# )
240-
# sid_match, nonce_match = self.extract_sid_nonce(response.text)
241-
242-
# if not sid_match or not nonce_match:
243-
# print(
244-
# "Failed to get SID or nonce. Trying to update cookies automatically..."
245-
# )
246-
# self._set_cookies_automatically()
247-
# response = requests.get(
248-
# url, cookies=self.cookies
249-
# )
250-
# sid_match, nonce_match = self.extract_sid_nonce(response.text)
251-
252-
# if not nonce_match:
253-
# if self.nonce:
254-
# return (sid_match, self.nonce)
255-
# else:
256-
# raise Exception(
257-
# "Can not retrieve SID and nonce even after automatic cookie update."
258-
# )
259-
# return (sid_match.group(1), nonce_match.group(1))
260-
261-
# except Exception as e:
262-
# raise ConnectionError(
263-
# f"Failed to retrive SID or Nonce valuse:\n{e}"
264-
# )
265-
266140
@staticmethod
267141
def extract_sid_nonce(response_text):
268142
sid_match = re.search(r'"FdrFJe":"([\d-]+)"', response_text)
@@ -407,3 +281,129 @@ def generate_custom_content(self, prompt: str, *custom_parsers) -> str:
407281
continue
408282
print("Parsing failed; returning original text. Consider using CustomParser.")
409283
return response_text
284+
285+
def check_session_cookies(self) -> None:
286+
"""
287+
Prints the session's cookies. Indicates if the session is uninitialized.
288+
"""
289+
if self.session:
290+
cookies = self.session.cookies.get_dict()
291+
cookies_str = "\n".join(f"{key}: {value}" for key, value in cookies.items())
292+
print(f"Session Cookies:\n{cookies_str}")
293+
else:
294+
print("Session not initialized.")
295+
296+
def check_session_headers(self) -> None:
297+
"""
298+
Prints the session's headers. Indicates if the session is uninitialized.
299+
"""
300+
if self.session:
301+
headers = self.session.headers
302+
headers_str = "\n".join(f"{key}: {value}" for key, value in headers.items())
303+
print(f"Session Headers:\n{headers_str}")
304+
else:
305+
print("Session not initialized.")
306+
307+
def _set_cookies_automatically(self) -> None:
308+
"""
309+
Updates the instance's cookies attribute with Gemini API tokens, either from environment variables or by extracting them from the browser, based on the auto_cookies flag.
310+
"""
311+
if len(getattr(self, "cookies", {})) > 5:
312+
return
313+
314+
if self.auto_cookies:
315+
try:
316+
self._update_cookies_from_browser()
317+
if not self.cookies:
318+
raise ValueError("No cookies were loaded from the browser.")
319+
except Exception as e:
320+
raise Exception("Failed to extract cookies from browser.") from e
321+
else:
322+
print(
323+
"Cookie loading issue, try setting auto_cookies to True. Restart browser, log out, log in for Gemini Web UI to work. Keep a single browser open."
324+
)
325+
try:
326+
self.auto_cookies = True
327+
self._update_cookies_from_browser()
328+
if not self.cookies:
329+
raise ValueError("No cookies were loaded from the browser.")
330+
except Exception as e:
331+
print(f"Automatic cookie retrieval failed: {e}")
332+
333+
if not self.cookies:
334+
raise Exception(
335+
"Gemini cookies must be provided through environment variables or extracted from the browser with auto_cookies enabled."
336+
)
337+
338+
def _update_cookies_from_browser(self) -> dict:
339+
"""
340+
Attempts to extract specific Gemini cookies from the cookies stored by web browsers on the current system.
341+
342+
This method iterates over a predefined list of supported browsers, attempting to retrieve cookies that match a specific domain (e.g., ".google.com"). If the required cookies are found, they are added to the instance's cookie store. The process supports multiple modern web browsers across different operating systems.
343+
344+
The method updates the instance's `cookies` attribute with any found cookies that match the specified criteria.
345+
346+
Raises:
347+
ValueError: If no supported browser is found with the required cookies, or if an essential cookie is missing after attempting retrieval from all supported browsers.
348+
"""
349+
350+
for browser_fn in SUPPORTED_BROWSERS:
351+
try:
352+
print(
353+
f"Trying to automatically retrieve cookies from {browser_fn} using the browser_cookie3 package."
354+
)
355+
cj = browser_fn(domain_name=".google.com")
356+
found_cookies = {cookie.name: cookie.value for cookie in cj}
357+
if len(found_cookies) >= 5:
358+
print(
359+
f"Successfully retrieved cookies from {browser_fn}.\n{found_cookies}"
360+
)
361+
self.cookies = found_cookies
362+
break
363+
else:
364+
print(
365+
f"Automatically configure cookies with detected ones but found only {len(found_cookies)} cookies.\n{found_cookies}"
366+
)
367+
except Exception as e:
368+
print(e)
369+
continue
370+
371+
if not self.cookies:
372+
raise ValueError(
373+
"Failed to get cookies. Set 'cookies' argument or 'auto_cookies' as True."
374+
)
375+
376+
# def _set_sid_and_nonce(self) -> Tuple[str, str]:
377+
# """
378+
# Retrieves the session ID (SID) and a SNlM0e nonce value from the application page.
379+
# """
380+
# url = f"{HOST}/app"
381+
# try:
382+
# response = requests.get(
383+
# url, cookies=self.cookies
384+
# )
385+
# sid_match, nonce_match = self.extract_sid_nonce(response.text)
386+
387+
# if not sid_match or not nonce_match:
388+
# print(
389+
# "Failed to get SID or nonce. Trying to update cookies automatically..."
390+
# )
391+
# self._set_cookies_automatically()
392+
# response = requests.get(
393+
# url, cookies=self.cookies
394+
# )
395+
# sid_match, nonce_match = self.extract_sid_nonce(response.text)
396+
397+
# if not nonce_match:
398+
# if self.nonce:
399+
# return (sid_match, self.nonce)
400+
# else:
401+
# raise Exception(
402+
# "Can not retrieve SID and nonce even after automatic cookie update."
403+
# )
404+
# return (sid_match.group(1), nonce_match.group(1))
405+
406+
# except Exception as e:
407+
# raise ConnectionError(
408+
# f"Failed to retrive SID or Nonce valuse:\n{e}"
409+
# )

0 commit comments

Comments
 (0)