-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdeep_api.py
More file actions
200 lines (174 loc) · 9.06 KB
/
deep_api.py
File metadata and controls
200 lines (174 loc) · 9.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
"""
░░░░▒▓▓▓▓▓▓▓▓▓▓▒░░░░░
░░░▒▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▒░░░
░▒▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▒░░
░▒▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▒░░
░░░▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░
░░▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░
░░▓▓▓▓▓▓▓▓▓▒▒▒▒▒▒░░░▒▓▓▓▓▒░▓▓▓▓▓▓▓▓▓▓▓░░
░▓▓▓▓▓▓▒░░░░░ ░▓▓▓▓▓▒ ░░▒▓▓▒▒░░▓▓▓░
░▓▓▓▓▓░░░░ ░░▒▓▓▓░░ ░░░ ░▒▓▓▓▒
▒▓▓▓▓░░░░ ░░▒▓▓░░░ ░░░▓▓▓▓▓▓
▓▓▓▓░░░▒▒▒░░░░ ░░░░░░▒▒░░░▓▓▓▓▓▓▓▓▓
▓▓▓▓░░▒▓▓▓▓▓▓▓░░ ░░▓▒░░░ ░░░▓▓▓▓▓▓▓▓▓
▒▓▓▓░░░▓▓▓▓▓▓▓▓▓░░ ░░▒▓▓░ ░░▒▓▓▓▓▓▓▓▓▓
▒▓▓▓▒░░▒▓▓▓▓▓▓▓▓▓▒░░░ ░░░░ ░░▓▓▓▓▓▓▓▓▓▒
░▓▓▓▓░░░▒▓▓▓▓▓▓▓▓▓▓░░ ░░▓▓▓▓▓▓▓▓▓▓░
░░▓▓▓▓░░░░▓▓▓▓░░▒▓▓▓░░░ ░░▒▓▓▓▓▓▓▓▓▓▓░░
░░░▓▓▓▓▒░░░░▒▓▓░░░░▓▓▓░░ ░░░▒▓▓▓▓▓▓▓▓░░░
░░▓▓▓▓▓▒░░░░░░ ░░░▒▒░░░░▓▓▓▓▓▓▓░░░
░░▒▓▓▓▓▓▓▓▒░░░░░▒▒▓▓▓▓▓▓▓▓▓▓▓▓▓▒░░░
░░▒▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▒░░░░
░░▒▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▒░░░░
░░░░▒▓▓▓▓▓▓▓▓▓▓▒░░░░░░ """
print("""
░█▀▀▄ ░█▀▀▀ ░█▀▀▀ ░█▀▀█ ── ─█▀▀█ ░█▀▀█ ▀█▀
░█─░█ ░█▀▀▀ ░█▀▀▀ ░█▄▄█ ▀▀ ░█▄▄█ ░█▄▄█ ░█─
░█▄▄▀ ░█▄▄▄ ░█▄▄▄ ░█─── ── ░█─░█ ░█─── ▄█▄
the free api library of deepseek
by b1t0ne
tg: https://t.me/u53rnm3
github: https://github.com/b1t0nese""")
from undetected_chromedriver import Chrome
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import psutil
def close_processes(process_names):
for proc in psutil.process_iter():
for name in process_names:
if name.lower() in proc.name().lower():
proc.kill()
print(f"Process {proc.pid} ({proc.name()}) has been terminated.")
# команда для закрытия всех процессов связанных с chrome
#желательно использовать при импорте библиотеки если ваша программа часто перезапускается
def close_chromedrivers():
process_names = ["chrome.exe", "chromedriver.exe"]
close_processes(process_names)
class UserTokenError(Exception):
def __init__(self, message="Invalid userToken", code=400):
self.code = code
super().__init__(f"{message} (code: {code})")
class dpsk:
# Инициирование deepseek, получает на вход 3 аргумента максимум
#- ваш userToken с сайта дипсик (важно), промпт дипсику
def __init__(self, userToken, prompt=None, headless=True):
print("Chrome initialization...")
self.driver = Chrome(headless=headless)
self.driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
"source": """
Object.defineProperty(navigator, 'webdriver', {
get: () => undefined
});
"""
})
self.count_msgs = 0
self.prompt = prompt
print("Starting DeepSeek...")
self.driver.get("https://chat.deepseek.com")
local_storage = self.driver.execute_script("return window.localStorage;")
local_storage['userToken'] = json.dumps({"value": userToken, "__version": "0"})
self.driver.execute_script("window.localStorage.clear();")
for key, value in local_storage.items():
self.driver.execute_script(f"window.localStorage.setItem('{key}', '{value}');")
self.driver.get("https://chat.deepseek.com")
self.del_history(prompt=prompt)
def get_message(self):
result = None
try:
markdown_blocks = self.driver.find_elements(By.CSS_SELECTOR, 'div.ds-markdown.ds-markdown--block')
if self.count_msgs+1==len(markdown_blocks):
target_markdown = markdown_blocks[self.count_msgs]
if target_markdown.find_element(By.XPATH, './following-sibling::div[contains(@class, "ds-flex")][1]'):
result = target_markdown.text
except: pass
try:
busy_server = self.driver.find_element(
By.XPATH, "//span[text()='Server busy, please try again later.']")
if busy_server:
result = "break"
except: pass
try:
busy_server = self.driver.find_element(
By.XPATH, "//span[text()='Check network and retry.']")
if busy_server:
result = "break"
except: pass
return result
# Команда для запроса нейронке, на вход подаётся текст и параметры - глубокое размышление и поиск
def chat(self, text, think=False, search=False):
buttons = self.driver.find_elements(By.CSS_SELECTOR, ".ds-button.ds-button--primary.ds-button--filled")
if think:
buttons[0].click()
if search:
buttons[1].click()
chat_input = self.driver.find_element("id", "chat-input")
while not chat_input.get_attribute('value'):
chat_input.clear()
text_chunks = [text[i:i+50] for i in range(0, len(text), 50)]
while not chat_input.get_attribute('value'):
for chunk in text_chunks:
if "\n" in chunk:
parts = chunk.split("\n")
for i, part in enumerate(parts):
if part:
chat_input.send_keys(part)
if i != len(parts)-1:
chat_input.send_keys(Keys.SHIFT + Keys.ENTER)
else:
chat_input.send_keys(chunk)
chat_input.send_keys(Keys.ENTER)
result = None
while not result:
result = self.get_message()
if result=="break":
result = None
break
self.count_msgs += 1
if think:
buttons[0].click()
if search:
buttons[1].click()
if not result:
self.count_msgs -= 1
self.driver.refresh()
return self.chat(text, think, search)
return result
# Команда для очистки истории (практически просто создаёт новый чат), можно задать промпт
def del_history(self, prompt=None):
self.count_msgs = 0
self.driver.get("https://chat.deepseek.com")
if not self.driver.current_url=="https://chat.deepseek.com/sign_in":
print("DeepSeek started!\n\n")
else:
self.driver.quit()
raise UserTokenError("invalid userToken")
if prompt or self.prompt:
print("Sending prompt to DeepSeek...")
if prompt:
self.prompt = prompt
self.chat(self.prompt)
print("Complete!\n")
# Простой пример использования api
if __name__=="__main__":
userToken = "your userToken"
prompt = "Ты обычный DeepSeek."
chat = dpsk(userToken, prompt=prompt)
try:
while True:
inpt = input("Message DeepSeek: ")
if inpt=="exit":
chat.driver.quit()
exit()
elif inpt=="refresh":
chat.refresh()
continue
think = False
search = False
if "#THINK" in inpt:
think = True
if "#SEARCH" in inpt:
search = True
print("DeepSeek:", chat.chat(inpt, think=think, search=search)+"\n")
except KeyboardInterrupt:
chat.driver.quit()
exit()