habulaj commited on
Commit
df62731
·
verified ·
1 Parent(s): d8423f7

Create utils.py

Browse files
Files changed (1) hide show
  1. gemini_client/utils.py +248 -0
gemini_client/utils.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ import json
3
+ import mimetypes
4
+ from pathlib import Path
5
+ from typing import Dict, Tuple, Union, Optional
6
+
7
+ from curl_cffi import CurlError, CurlMime
8
+ from curl_cffi.requests import AsyncSession
9
+ from requests.exceptions import RequestException, HTTPError, Timeout # Added Timeout
10
+
11
+ from rich.console import Console
12
+
13
+ # Assuming Endpoint and Headers enums are in 'enums.py' within the same package
14
+ from .enums import Endpoint, Headers
15
+
16
+ console = Console() # Instantiate console for logging
17
+
18
+ async def upload_file(
19
+ file: Union[bytes, str, Path],
20
+ proxy: Optional[Union[str, Dict[str, str]]] = None,
21
+ impersonate: str = "chrome110"
22
+ ) -> str:
23
+ """
24
+ Uploads a file to Google's Gemini server using curl_cffi and returns its identifier.
25
+
26
+ Args:
27
+ file (bytes | str | Path): File data in bytes or path to the file to be uploaded.
28
+ proxy (str | dict, optional): Proxy URL or dictionary for the request.
29
+ impersonate (str, optional): Browser profile for curl_cffi to impersonate. Defaults to "chrome110".
30
+
31
+ Returns:
32
+ str: Identifier of the uploaded file.
33
+
34
+ Raises:
35
+ HTTPError: If the upload request fails.
36
+ RequestException: For other network-related errors.
37
+ FileNotFoundError: If the file path does not exist.
38
+ """
39
+ # Prepare proxy dictionary for curl_cffi
40
+ proxies_dict = None
41
+ if isinstance(proxy, str):
42
+ proxies_dict = {"http": proxy, "https": proxy} # curl_cffi uses http/https keys
43
+ elif isinstance(proxy, dict):
44
+ proxies_dict = proxy # Assume it's already in the correct format
45
+
46
+ # Create CurlMime object for multipart upload
47
+ mp = CurlMime()
48
+
49
+ try:
50
+ # Handle file input - determine content type and filename
51
+ if isinstance(file, bytes):
52
+ # If bytes, we can't determine type, default to image/jpeg
53
+ # User should provide file path for better type detection
54
+ content_type = "image/jpeg"
55
+ filename = "file.jpg"
56
+ mp.addpart(
57
+ name="file",
58
+ content_type=content_type,
59
+ filename=filename,
60
+ data=file
61
+ )
62
+ else:
63
+ # If path, use the file directly
64
+ file_path = Path(file)
65
+ if not file_path.is_file():
66
+ raise FileNotFoundError(f"File not found at path: {file}")
67
+
68
+ # Determine content type from file extension
69
+ content_type, _ = mimetypes.guess_type(str(file_path))
70
+ if not content_type:
71
+ # Try to guess from extension
72
+ ext = file_path.suffix.lower()
73
+ if ext in ['.mp4', '.avi', '.mov', '.webm', '.mkv', '.flv', '.m4v']:
74
+ content_type = "video/mp4"
75
+ elif ext in ['.mp3', '.wav', '.ogg', '.flac', '.aac', '.m4a', '.wma']:
76
+ content_type = "audio/mpeg"
77
+ elif ext in ['.jpg', '.jpeg']:
78
+ content_type = "image/jpeg"
79
+ elif ext == '.png':
80
+ content_type = "image/png"
81
+ elif ext == '.gif':
82
+ content_type = "image/gif"
83
+ elif ext == '.webp':
84
+ content_type = "image/webp"
85
+ else:
86
+ # Default to image/jpeg if can't determine
87
+ content_type = "image/jpeg"
88
+
89
+ mp.addpart(
90
+ name="file",
91
+ content_type=content_type,
92
+ filename=file_path.name,
93
+ local_path=str(file_path)
94
+ )
95
+
96
+ # Use AsyncSession from curl_cffi
97
+ async with AsyncSession(
98
+ proxies=proxies_dict,
99
+ impersonate=impersonate,
100
+ headers=Headers.UPLOAD.value # Pass headers directly
101
+ # follow_redirects is handled automatically by curl_cffi
102
+ ) as client:
103
+ response = await client.post(
104
+ url=Endpoint.UPLOAD.value, # Use Endpoint enum
105
+ multipart=mp,
106
+ )
107
+ response.raise_for_status() # Raises HTTPError for bad responses
108
+ result = response.text
109
+ return result
110
+ except HTTPError as e:
111
+ console.log(f"[red]HTTP error during file upload: {e.response.status_code} {e}[/red]")
112
+ raise # Re-raise HTTPError
113
+ except (RequestException, CurlError) as e: # Catch CurlError as well
114
+ console.log(f"[red]Network error during file upload: {e}[/red]")
115
+ raise # Re-raise other request errors
116
+ finally:
117
+ # Always close the multipart object to free memory
118
+ mp.close()
119
+
120
+ def load_cookies(cookie_path: str) -> Tuple[str, str, Dict[str, str]]:
121
+ """
122
+ Loads authentication cookies from a JSON file or Netscape HTTP Cookie File format.
123
+ Supports both formats and can read them from the same file.
124
+
125
+ Args:
126
+ cookie_path (str): Path to the file containing cookies (JSON or Netscape format).
127
+
128
+ Returns:
129
+ tuple[str, str, dict]: Tuple containing __Secure-1PSID, __Secure-1PSIDTS, and additional cookies dict.
130
+
131
+ Raises:
132
+ Exception: If the file is not found, invalid, or required cookies are missing.
133
+ """
134
+ try:
135
+ with open(cookie_path, 'r', encoding='utf-8') as file:
136
+ content = file.read()
137
+
138
+ session_auth1 = None
139
+ session_auth2 = None
140
+ additional_cookies = {}
141
+
142
+ # Try to parse JSON format first
143
+ json_end = content.find(']')
144
+ if json_end == -1:
145
+ json_end = content.find('}')
146
+ if json_end != -1:
147
+ try:
148
+ json_content = content[:json_end + 1]
149
+ cookies = json.loads(json_content)
150
+
151
+ for item in cookies:
152
+ name_upper = item['name'].upper()
153
+ if name_upper == '__SECURE-1PSID':
154
+ session_auth1 = item['value']
155
+ elif name_upper == '__SECURE-1PSIDTS':
156
+ session_auth2 = item['value']
157
+ else:
158
+ # Store additional cookies (like COMPASS, _ga_WC57KJ50ZZ, etc.)
159
+ additional_cookies[item['name']] = item['value']
160
+ except json.JSONDecodeError:
161
+ pass # Fall through to Netscape format parsing
162
+
163
+ # Also parse Netscape HTTP Cookie File format
164
+ # Format: domain\tflag\tpath\tsecure\texpiration\tname\tvalue
165
+ for line in content.split('\n'):
166
+ line = line.strip()
167
+ # Skip comments and empty lines
168
+ if not line or line.startswith('#'):
169
+ continue
170
+
171
+ # Parse Netscape cookie format
172
+ parts = line.split('\t')
173
+ if len(parts) >= 7:
174
+ domain = parts[0].strip()
175
+ name = parts[5].strip()
176
+ value = parts[6].strip()
177
+
178
+ # Look for cookies from .gemini.google.com or .google.com
179
+ if '.gemini.google.com' in domain or '.google.com' in domain:
180
+ name_upper = name.upper()
181
+ if name_upper == '__SECURE-1PSID':
182
+ if not session_auth1: # Only use if not already set from JSON
183
+ session_auth1 = value
184
+ elif name_upper == '__SECURE-1PSIDTS':
185
+ if not session_auth2: # Only use if not already set from JSON
186
+ session_auth2 = value
187
+ else:
188
+ # Store additional cookies (like COMPASS, _ga_WC57KJ50ZZ, etc.)
189
+ additional_cookies[name] = value
190
+
191
+ if not session_auth1 or not session_auth2:
192
+ raise StopIteration("Required cookies (__Secure-1PSID or __Secure-1PSIDTS) not found.")
193
+
194
+ return session_auth1, session_auth2, additional_cookies
195
+ except FileNotFoundError:
196
+ raise Exception(f"Cookie file not found at path: {cookie_path}")
197
+ except StopIteration as e:
198
+ raise Exception(f"{e} Check the cookie file format and content.")
199
+ except Exception as e: # Catch other potential errors
200
+ raise Exception(f"An unexpected error occurred while loading cookies: {e}")
201
+
202
+ def save_cookies(cookie_path: str, secure_1psid: str, secure_1psidts: str, additional_cookies: Optional[Dict[str, str]] = None) -> None:
203
+ """
204
+ Saves authentication cookies to a JSON file.
205
+ Updates existing cookies or creates a new file if it doesn't exist.
206
+
207
+ Args:
208
+ cookie_path (str): Path to the JSON file where cookies will be saved.
209
+ secure_1psid (str): The __Secure-1PSID cookie value.
210
+ secure_1psidts (str): The __Secure-1PSIDTS cookie value.
211
+ additional_cookies (dict, optional): Additional cookies to save (e.g., COMPASS).
212
+
213
+ Raises:
214
+ Exception: If there's an error writing to the file.
215
+ """
216
+ try:
217
+ cookies_list = [
218
+ {
219
+ "name": "__Secure-1PSID",
220
+ "value": secure_1psid
221
+ },
222
+ {
223
+ "name": "__Secure-1PSIDTS",
224
+ "value": secure_1psidts
225
+ }
226
+ ]
227
+
228
+ # Add additional cookies if provided
229
+ if additional_cookies:
230
+ for name, value in additional_cookies.items():
231
+ # Skip if already in the list
232
+ if not any(cookie["name"] == name for cookie in cookies_list):
233
+ cookies_list.append({
234
+ "name": name,
235
+ "value": value
236
+ })
237
+
238
+ # Ensure directory exists
239
+ Path(cookie_path).parent.mkdir(parents=True, exist_ok=True)
240
+
241
+ # Write to file
242
+ with open(cookie_path, 'w', encoding='utf-8') as f:
243
+ json.dump(cookies_list, f, indent=4, ensure_ascii=False)
244
+
245
+ console.log(f"[green]Cookies atualizados e salvos em {cookie_path}[/green]")
246
+ except Exception as e:
247
+ console.log(f"[red]Erro ao salvar cookies: {e}[/red]")
248
+ raise Exception(f"Erro ao salvar cookies: {e}")