gemixy 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- gemini/__init__.py +15 -0
- gemini/core.py +162 -0
- gemixy/__init__.py +57 -0
- gemixy-1.0.0.dist-info/METADATA +19 -0
- gemixy-1.0.0.dist-info/RECORD +8 -0
- gemixy-1.0.0.dist-info/WHEEL +5 -0
- gemixy-1.0.0.dist-info/licenses/LICENSE +21 -0
- gemixy-1.0.0.dist-info/top_level.txt +2 -0
gemini/__init__.py
ADDED
gemini/core.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import re
|
|
3
|
+
import uuid
|
|
4
|
+
import time
|
|
5
|
+
import requests
|
|
6
|
+
|
|
7
|
+
def extract_snlm0e_token(html):
|
|
8
|
+
for pattern in [r'"SNlM0e":"([^"]+)"', r'"FdrFJe":"([^"]+)"', r'"cfb2h":"([^"]+)"']:
|
|
9
|
+
match = re.search(pattern, html)
|
|
10
|
+
if match and len(match.group(1)) > 20:
|
|
11
|
+
return match.group(1)
|
|
12
|
+
return None
|
|
13
|
+
|
|
14
|
+
def extract_build_params(html):
|
|
15
|
+
params = {}
|
|
16
|
+
bl = re.search(r'boq[_-]assistant[^"\']*_(\d+\.\d+[^"\']*)', html)
|
|
17
|
+
if bl:
|
|
18
|
+
params['bl'] = f'boq_assistant-bard-web-server_{bl.group(1)}'
|
|
19
|
+
fsid = re.search(r'f\.sid["\']?\s*[:=]\s*["\']?([^"\'&\s]+)', html)
|
|
20
|
+
if fsid:
|
|
21
|
+
params['fsid'] = fsid.group(1)
|
|
22
|
+
reqid = re.search(r'_reqid["\']?\s*[:=]\s*["\']?(\d+)', html)
|
|
23
|
+
if reqid:
|
|
24
|
+
params['reqid'] = int(reqid.group(1))
|
|
25
|
+
params.setdefault('bl', 'boq_assistant-bard-web-server_20251217.07_p5')
|
|
26
|
+
params.setdefault('fsid', str(-1 * int(time.time() * 1000)))
|
|
27
|
+
params.setdefault('reqid', int(time.time() * 1000) % 1000000)
|
|
28
|
+
return params
|
|
29
|
+
|
|
30
|
+
def get_session():
|
|
31
|
+
session = requests.Session()
|
|
32
|
+
headers = {
|
|
33
|
+
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
|
|
34
|
+
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
|
|
35
|
+
'Accept-Language': 'en-US,en;q=0.9',
|
|
36
|
+
}
|
|
37
|
+
resp = session.get('https://gemini.google.com/app', headers=headers, timeout=30)
|
|
38
|
+
snlm0e = extract_snlm0e_token(resp.text)
|
|
39
|
+
if not snlm0e:
|
|
40
|
+
return None
|
|
41
|
+
params = extract_build_params(resp.text)
|
|
42
|
+
return {'session': session, 'snlm0e': snlm0e, **params}
|
|
43
|
+
|
|
44
|
+
def build_payload(prompt, snlm0e):
|
|
45
|
+
escaped = prompt.replace('\\', '\\\\').replace('"', '\\"').replace('\n', '\\n')
|
|
46
|
+
rid = str(uuid.uuid4()).upper()
|
|
47
|
+
payload = [
|
|
48
|
+
[escaped, 0, None, None, None, None, 0],
|
|
49
|
+
["en-US"],
|
|
50
|
+
["", "", "", None, None, None, None, None, None, ""],
|
|
51
|
+
snlm0e, uuid.uuid4().hex, None, [0], 1,
|
|
52
|
+
None, None, 1, 0, None, None, None, None, None,
|
|
53
|
+
[[0]], 0, None, None, None, None, None, None, None, None, 1, None, None,
|
|
54
|
+
[4], None, None, None, None, None, None, None, None, None, None,
|
|
55
|
+
[2], None, None, None, None, None, None, None, None, None, None, None,
|
|
56
|
+
0, None, None, None, None, None, rid, None, []
|
|
57
|
+
]
|
|
58
|
+
p = json.dumps(payload, separators=(',', ':')).replace('\\', '\\\\').replace('"', '\\"')
|
|
59
|
+
return {'f.req': f'[null,"{p}"]', '': ''}
|
|
60
|
+
|
|
61
|
+
def parse_response(text):
|
|
62
|
+
full = ""
|
|
63
|
+
for line in text.strip().split('\n'):
|
|
64
|
+
if not line or line.startswith(')]}'):
|
|
65
|
+
continue
|
|
66
|
+
try:
|
|
67
|
+
data = json.loads(line)
|
|
68
|
+
if isinstance(data, list) and data[0][0] == "wrb.fr" and len(data[0]) > 2:
|
|
69
|
+
inner = data[0][2]
|
|
70
|
+
if inner:
|
|
71
|
+
parsed = json.loads(inner)
|
|
72
|
+
if isinstance(parsed, list) and len(parsed) > 4:
|
|
73
|
+
content = parsed[4]
|
|
74
|
+
if isinstance(content, list) and len(content) > 0:
|
|
75
|
+
item = content[0]
|
|
76
|
+
if isinstance(item, list) and len(item) > 1:
|
|
77
|
+
arr = item[1]
|
|
78
|
+
if isinstance(arr, list) and len(arr) > 0 and isinstance(arr[0], str):
|
|
79
|
+
if len(arr[0]) > len(full):
|
|
80
|
+
full = arr[0]
|
|
81
|
+
except Exception:
|
|
82
|
+
continue
|
|
83
|
+
return full.replace('\\n', '\n').replace('\\"', '"').replace('\\\\', '\\') if full else None
|
|
84
|
+
|
|
85
|
+
def chat_with_gemini(prompt):
|
|
86
|
+
data = get_session()
|
|
87
|
+
if not data:
|
|
88
|
+
return None
|
|
89
|
+
sess = data['session']
|
|
90
|
+
url = (f"https://gemini.google.com/_/BardChatUi/data/assistant.lamda.BardFrontendService/StreamGenerate"
|
|
91
|
+
f"?bl={data['bl']}&f.sid={data['fsid']}&hl=en-US&_reqid={data['reqid']}&rt=c")
|
|
92
|
+
cookie = '; '.join(f"{k}={v}" for k, v in sess.cookies.items())
|
|
93
|
+
headers = {
|
|
94
|
+
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
|
|
95
|
+
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
|
|
96
|
+
'x-same-domain': '1',
|
|
97
|
+
'origin': 'https://gemini.google.com',
|
|
98
|
+
'referer': 'https://gemini.google.com/',
|
|
99
|
+
'Cookie': cookie,
|
|
100
|
+
}
|
|
101
|
+
resp = sess.post(url, data=build_payload(prompt, data['snlm0e']), headers=headers, timeout=60)
|
|
102
|
+
if resp.status_code != 200:
|
|
103
|
+
return None
|
|
104
|
+
return parse_response(resp.text)
|
|
105
|
+
|
|
106
|
+
def messages_to_prompt(messages):
|
|
107
|
+
parts = []
|
|
108
|
+
for m in messages:
|
|
109
|
+
role = m.get("role", "user")
|
|
110
|
+
content = m.get("content", "")
|
|
111
|
+
if isinstance(content, str):
|
|
112
|
+
if role == "system":
|
|
113
|
+
parts.append(f"[System]: {content}")
|
|
114
|
+
elif role == "assistant":
|
|
115
|
+
parts.append(f"[Assistant]: {content}")
|
|
116
|
+
else:
|
|
117
|
+
parts.append(content)
|
|
118
|
+
elif isinstance(content, list):
|
|
119
|
+
for item in content:
|
|
120
|
+
if isinstance(item, dict) and item.get("type") == "text":
|
|
121
|
+
parts.append(item.get("text", ""))
|
|
122
|
+
return "\n".join(parts)
|
|
123
|
+
|
|
124
|
+
def ok_response(text, model, req_id=None):
|
|
125
|
+
return {
|
|
126
|
+
"id": req_id or f"chatcmpl-{uuid.uuid4().hex}",
|
|
127
|
+
"object": "chat.completion",
|
|
128
|
+
"created": int(time.time()),
|
|
129
|
+
"model": model,
|
|
130
|
+
"choices": [{
|
|
131
|
+
"index": 0,
|
|
132
|
+
"message": {"role": "assistant", "content": text},
|
|
133
|
+
"finish_reason": "stop"
|
|
134
|
+
}],
|
|
135
|
+
"usage": {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
def chunk_response(text, resp_id, created, model):
|
|
139
|
+
return {
|
|
140
|
+
"id": resp_id,
|
|
141
|
+
"object": "chat.completion.chunk",
|
|
142
|
+
"created": created,
|
|
143
|
+
"model": model,
|
|
144
|
+
"choices": [{
|
|
145
|
+
"index": 0,
|
|
146
|
+
"delta": {"content": text},
|
|
147
|
+
"finish_reason": None
|
|
148
|
+
}]
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
def chunk_done(resp_id, created, model):
|
|
152
|
+
return {
|
|
153
|
+
"id": resp_id,
|
|
154
|
+
"object": "chat.completion.chunk",
|
|
155
|
+
"created": created,
|
|
156
|
+
"model": model,
|
|
157
|
+
"choices": [{
|
|
158
|
+
"index": 0,
|
|
159
|
+
"delta": {},
|
|
160
|
+
"finish_reason": "stop"
|
|
161
|
+
}]
|
|
162
|
+
}
|
gemixy/__init__.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import sys
|
|
3
|
+
import json
|
|
4
|
+
from typing import List, Iterator
|
|
5
|
+
|
|
6
|
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
7
|
+
from gemini.core import chat_with_gemini, messages_to_prompt
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class GeminiClient:
|
|
11
|
+
def __init__(self, base_url: str = None, api_key: str = "any"):
|
|
12
|
+
self.base_url = base_url
|
|
13
|
+
self.api_key = api_key
|
|
14
|
+
|
|
15
|
+
def chat(self, message: str, model: str = "gemini", **kwargs) -> str:
|
|
16
|
+
result = chat_with_gemini(message)
|
|
17
|
+
if not result:
|
|
18
|
+
raise RuntimeError("Gemini did not respond")
|
|
19
|
+
return result
|
|
20
|
+
|
|
21
|
+
def chat_stream(self, message: str, model: str = "gemini", **kwargs) -> Iterator[str]:
|
|
22
|
+
result = chat_with_gemini(message)
|
|
23
|
+
if not result:
|
|
24
|
+
raise RuntimeError("Gemini did not respond")
|
|
25
|
+
for word in result.split():
|
|
26
|
+
yield word + " "
|
|
27
|
+
|
|
28
|
+
def messages(self, messages: List[dict], model: str = "gemini", **kwargs) -> str:
|
|
29
|
+
prompt = messages_to_prompt(messages)
|
|
30
|
+
result = chat_with_gemini(prompt)
|
|
31
|
+
if not result:
|
|
32
|
+
raise RuntimeError("Gemini did not respond")
|
|
33
|
+
return result
|
|
34
|
+
|
|
35
|
+
def messages_stream(self, messages: List[dict], model: str = "gemini", **kwargs) -> Iterator[str]:
|
|
36
|
+
prompt = messages_to_prompt(messages)
|
|
37
|
+
result = chat_with_gemini(prompt)
|
|
38
|
+
if not result:
|
|
39
|
+
raise RuntimeError("Gemini did not respond")
|
|
40
|
+
for word in result.split():
|
|
41
|
+
yield word + " "
|
|
42
|
+
|
|
43
|
+
def models(self) -> dict:
|
|
44
|
+
return {
|
|
45
|
+
"object": "list",
|
|
46
|
+
"data": [
|
|
47
|
+
{
|
|
48
|
+
"id": "gemini",
|
|
49
|
+
"object": "model",
|
|
50
|
+
"created": 1686935002,
|
|
51
|
+
"owned_by": "google"
|
|
52
|
+
}
|
|
53
|
+
]
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
client = GeminiClient()
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: gemixy
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Python SDK for Gemini OpenAI Proxy
|
|
5
|
+
Author: pooraddyy
|
|
6
|
+
License: MIT
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Requires-Python: >=3.8
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: requests>=2.28.0
|
|
13
|
+
Dynamic: author
|
|
14
|
+
Dynamic: classifier
|
|
15
|
+
Dynamic: license
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
Dynamic: requires-dist
|
|
18
|
+
Dynamic: requires-python
|
|
19
|
+
Dynamic: summary
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
gemini/__init__.py,sha256=bWfcbK56Z0-hKUGCi-vima0zwWC9KTiu9D4_XZxAJmI,245
|
|
2
|
+
gemini/core.py,sha256=aIxlrIo7DGUfphfmPRlnXEDTR7V9OQU2h8TJ9DHlnWk,6200
|
|
3
|
+
gemixy/__init__.py,sha256=gIcipOGYvCHcAysO_P9-gObByBiffskZ-0_VlJ6IFEQ,1822
|
|
4
|
+
gemixy-1.0.0.dist-info/licenses/LICENSE,sha256=7I6lgG6ucXpRTrCd-UlRTtRJ6oW71CPV_y8rKtUm4RU,1066
|
|
5
|
+
gemixy-1.0.0.dist-info/METADATA,sha256=6SCc2deuHBGMEH4SEmUl17fK_G0QaieD6GIz8XYpXIY,488
|
|
6
|
+
gemixy-1.0.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
7
|
+
gemixy-1.0.0.dist-info/top_level.txt,sha256=kccPfROHDxIxTAH2B3t_0NeslG-jVHCM93vv14OhdFE,14
|
|
8
|
+
gemixy-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 pooraddyy
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|