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

Commit c304f29

Browse files
committed
feat: add load_cookies
1 parent 8ae4f28 commit c304f29

File tree

4 files changed

+43
-16
lines changed

4 files changed

+43
-16
lines changed

gemini/__init__.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,13 @@
1313
from .src.misc.constants import URLs, Headers
1414
from .src.misc.decorator import retry, log_method, time_execution, handle_errors
1515
from .src.misc.exceptions import PackageError, GeminiAPIError, TimeoutError
16-
from .src.misc.utils import extract_code, upload_image, max_token, max_sentence
16+
from .src.misc.utils import (
17+
extract_code,
18+
upload_image,
19+
max_token,
20+
max_sentence,
21+
load_cookies,
22+
)
1723

1824
from .src.extensions.replit import prepare_replit_data
1925

gemini/client.py

Lines changed: 2 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from requests.exceptions import ConnectionError
1010
from typing import Optional, Tuple, Dict, Union, List
1111

12-
from .src.misc.utils import upload_image
12+
from .src.misc.utils import upload_image, load_cookies
1313
from .src.model.parser.response_parser import ResponseParser
1414
from .src.model.output import GeminiCandidate, GeminiModelOutput
1515
from .src.model.parser.custom_parser import ParseMethod1, ParseMethod2
@@ -121,19 +121,7 @@ def _initialize_session(
121121
def _set_cookies_from_file(self, file_path: str) -> None:
122122
"""Loads cookies from a file and updates the session."""
123123
try:
124-
with open(file_path, "r") as file:
125-
if file_path.endswith(".json"):
126-
# Load JSON formatted cookies directly
127-
cookies = json.load(file)
128-
else:
129-
content = file.read()
130-
# Attempt to load Python dictionary formatted cookies
131-
try:
132-
content = content.replace("cookies = ", "").replace("'", '"')
133-
cookies = json.loads(content)
134-
except NameError:
135-
# Fallback to converting single quotes to double quotes and loading as JSON
136-
cookies = json.loads(content.replace("'", '"'))
124+
cookies = load_cookies(file_path)
137125
except Exception as e:
138126
raise Exception(f"Failed to load cookies from {file_path}: {e}")
139127

gemini/src/misc/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
from .constants import URLs, Headers
22
from .decorator import retry, log_method, time_execution, handle_errors
33
from .exceptions import PackageError, GeminiAPIError, TimeoutError
4-
from .utils import extract_code, upload_image, max_token, max_sentence
4+
from .utils import extract_code, upload_image, max_token, max_sentence, load_cookies

gemini/src/misc/utils.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,41 @@
1+
import json
12
import requests
23
from typing import Union
34
from gemini.src.misc.constants import Headers
45

56

7+
def load_cookies(file_path):
8+
"""
9+
Reads a text file and tries to parse it into a Python dictionary.
10+
Assumes the file might contain a cookies string or is in JSON format.
11+
12+
:param file_path: Path to the file containing cookie data
13+
:return: A dictionary containing cookie data
14+
"""
15+
with open(file_path, "r") as file:
16+
content = file.read().strip()
17+
18+
# If content includes '=', assume it's a cookie string
19+
if "=" in content:
20+
try:
21+
# Split at the first '=' and prepare for JSON parsing
22+
json_str = content.split("=", 1)[1].strip()
23+
json_str = json_str.replace(
24+
"'", '"'
25+
) # Replace single quotes with double quotes
26+
cookies_dict = json.loads(json_str)
27+
except json.JSONDecodeError:
28+
raise ValueError("The cookie string does not have a valid JSON format.")
29+
else:
30+
try:
31+
# Parse the entire content directly as JSON
32+
cookies_dict = json.loads(content)
33+
except json.JSONDecodeError:
34+
raise ValueError("The file content does not have a valid JSON format.")
35+
36+
return cookies_dict
37+
38+
639
def extract_code(text: str) -> str:
740
"""
841
Extracts code snippets from the given text.

0 commit comments

Comments
 (0)