Spaces:
Runtime error
Runtime error
File size: 11,807 Bytes
007bea3 94a0db1 007bea3 6b43710 007bea3 94a0db1 007bea3 |
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 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 |
from typing import Iterable, Dict
import streamlit as st
from os import listdir
from uuid import uuid4
from time import sleep, time
from threading import Thread
from json import loads, dumps
from random import getrandbits
from websocket import WebSocketApp
from requests import Session, get, post
class Perplexity:
def __init__(self, email: str = None) -> None:
self.session: Session = Session()
self.user_agent: dict = { "User-Agent": "Ask/2.4.1/224 (iOS; iPhone; Version 17.1) isiOSOnMac/false", "X-Client-Name": "Perplexity-iOS" }
self.session.headers.update(self.user_agent)
if email and ".perplexity_session" in listdir():
self._recover_session(email)
else:
self._init_session_without_login()
if email:
self._login(email)
self.email: str = email
self.t: str = self._get_t()
st.write(self.t)
self.sid: str = self._get_sid()
st.write(self.sid)
self.n: int = 1
self.base: int = 420
self.queue: list = []
self.finished: bool = True
self.last_uuid: str = None
self.backend_uuid: str = None # unused because we can't yet follow-up questions
self.frontend_session_id: str = str(uuid4())
assert self._ask_anonymous_user(), "failed to ask anonymous user"
self.ws: WebSocketApp = self._init_websocket()
self.ws_thread: Thread = Thread(target=self.ws.run_forever).start()
self._auth_session()
while not (self.ws.sock and self.ws.sock.connected):
sleep(0.01)
def _recover_session(self, email: str) -> None:
with open(".perplexity_session", "r") as f:
perplexity_session: dict = loads(f.read())
if email in perplexity_session:
self.session.cookies.update(perplexity_session[email])
else:
self._login(email, perplexity_session)
def _login(self, email: str, ps: dict = None) -> None:
self.session.post(url="https://www.perplexity.ai/api/auth/signin-email", data={"email": email})
email_link: str = str(input("paste the link you received by email: "))
self.session.get(email_link)
if ps:
ps[email] = self.session.cookies.get_dict()
else:
ps = {email: self.session.cookies.get_dict()}
with open(".perplexity_session", "w") as f:
f.write(dumps(ps))
def _init_session_without_login(self) -> None:
self.session.get(url=f"https://www.perplexity.ai/search/{str(uuid4())}")
self.session.headers.update(self.user_agent)
def _auth_session(self) -> None:
self.session.get(url="https://www.perplexity.ai/api/auth/session")
def _get_t(self) -> str:
return format(getrandbits(32), "08x")
def _get_sid(self) -> str:
return loads(self.session.get(
url=f"https://www.perplexity.ai/socket.io/?EIO=4&transport=polling&t={self.t}"
).text[1:])["sid"]
def _ask_anonymous_user(self) -> bool:
response = self.session.post(
url=f"https://www.perplexity.ai/socket.io/?EIO=4&transport=polling&t={self.t}&sid={self.sid}",
data="40{\"jwt\":\"anonymous-ask-user\"}"
).text
return response == "OK"
def _start_interaction(self) -> None:
self.finished = False
if self.n == 9:
self.n = 0
self.base *= 10
else:
self.n += 1
self.queue = []
def _get_cookies_str(self) -> str:
cookies = ""
for key, value in self.session.cookies.get_dict().items():
cookies += f"{key}={value}; "
return cookies[:-2]
def _write_file_url(self, filename: str, file_url: str) -> None:
if ".perplexity_files_url" in listdir():
with open(".perplexity_files_url", "r") as f:
perplexity_files_url: dict = loads(f.read())
else:
perplexity_files_url: dict = {}
perplexity_files_url[filename] = file_url
with open(".perplexity_files_url", "w") as f:
f.write(dumps(perplexity_files_url))
def _init_websocket(self) -> WebSocketApp:
def on_open(ws: WebSocketApp) -> None:
ws.send("2probe")
ws.send("5")
def on_message(ws: WebSocketApp, message: str) -> None:
if message == "2":
ws.send("3")
elif not self.finished:
if message.startswith("42"):
message : list = loads(message[2:])
content: dict = message[1]
if "mode" in content and content["mode"] == "copilot":
content["copilot_answer"] = loads(content["text"])
elif "mode" in content:
content.update(loads(content["text"]))
content.pop("text")
if (not ("final" in content and content["final"])) or ("status" in content and content["status"] == "completed"):
self.queue.append(content)
if message[0] == "query_answered":
self.last_uuid = content["uuid"]
self.finished = True
elif message.startswith("43"):
message: dict = loads(message[3:])[0]
if ("uuid" in message and message["uuid"] != self.last_uuid) or "uuid" not in message:
self.queue.append(message)
self.finished = True
return WebSocketApp(
url=f"wss://www.perplexity.ai/socket.io/?EIO=4&transport=websocket&sid={self.sid}",
header=self.user_agent,
cookie=self._get_cookies_str(),
on_open=on_open,
on_message=on_message,
on_error=lambda ws, err: print(f"websocket error: {err}")
)
def _s(self, query: str, mode: str = "concise", search_focus: str = "internet", attachments: list[str] = [], language: str = "en-GB", in_page: str = None, in_domain: str = None) -> None:
assert self.finished, "already searching"
assert mode in ["concise", "copilot"], "invalid mode"
assert len(attachments) <= 4, "too many attachments: max 4"
assert search_focus in ["internet", "scholar", "writing", "wolfram", "youtube", "reddit"], "invalid search focus"
if in_page:
search_focus = "in_page"
if in_domain:
search_focus = "in_domain"
self._start_interaction()
ws_message: str = f"{self.base + self.n}" + dumps([
"perplexity_ask",
query,
{
"version": "2.1",
"source": "default", # "ios"
"frontend_session_id": self.frontend_session_id,
"language": language,
"timezone": "CET",
"attachments": attachments,
"search_focus": search_focus,
"frontend_uuid": str(uuid4()),
"mode": mode,
# "use_inhouse_model": True
"in_page": in_page,
"in_domain": in_domain
}
])
self.ws.send(ws_message)
def search(self, query: str, mode: str = "concise", search_focus: str = "internet", attachments: list[str] = [], language: str = "en-GB", timeout: float = 30) -> Iterable[Dict]:
self._s(query, mode, search_focus, attachments, language)
start_time: float = time()
while (not self.finished) or len(self.queue) != 0:
if timeout and time() - start_time > timeout:
self.finished = True
return {"error": "timeout"}
if len(self.queue) != 0:
yield self.queue.pop(0)
def search_sync(self, query: str, mode: str = "concise", search_focus: str = "internet", attachments: list[str] = [], language: str = "en-GB", timeout: float = 30) -> dict:
self._s(query, mode, search_focus, attachments, language)
start_time: float = time()
while not self.finished:
if timeout and time() - start_time > timeout:
self.finished = True
return {"error": "timeout"}
return self.queue.pop(-1)
def upload(self, filename: str) -> str:
assert self.finished, "already searching"
assert filename.split(".")[-1] in ["txt", "pdf"], "invalid file format"
if filename.startswith("http"):
file = get(filename).content
else:
with open(filename, "rb") as f:
file = f.read()
self._start_interaction()
ws_message: str = f"{self.base + self.n}" + dumps([
"get_upload_url",
{
"version": "2.1",
"source": "default",
"content_type": "text/plain" if filename.split(".")[-1] == "txt" else "application/pdf",
}
])
self.ws.send(ws_message)
while not self.finished or len(self.queue) != 0:
if len(self.queue) != 0:
upload_data = self.queue.pop(0)
assert not upload_data["rate_limited"], "rate limited"
post(
url=upload_data["url"],
files={
"acl": (None, upload_data["fields"]["acl"]),
"Content-Type": (None, upload_data["fields"]["Content-Type"]),
"key": (None, upload_data["fields"]["key"]),
"AWSAccessKeyId": (None, upload_data["fields"]["AWSAccessKeyId"]),
"x-amz-security-token": (None, upload_data["fields"]["x-amz-security-token"]),
"policy": (None, upload_data["fields"]["policy"]),
"signature": (None, upload_data["fields"]["signature"]),
"file": (filename, file)
}
)
file_url: str = upload_data["url"] + upload_data["fields"]["key"].split("$")[0] + filename
self._write_file_url(filename, file_url)
return file_url
def threads(self, query: str = None, limit: int = None) -> list[dict]:
assert self.email, "not logged in"
assert self.finished, "already searching"
if not limit: limit = 20
data: dict = {"version": "2.1", "source": "default", "limit": limit, "offset": 0}
if query: data["search_term"] = query
self._start_interaction()
ws_message: str = f"{self.base + self.n}" + dumps([
"list_ask_threads",
data
])
self.ws.send(ws_message)
while not self.finished or len(self.queue) != 0:
if len(self.queue) != 0:
return self.queue.pop(0)
def list_autosuggest(self, query: str = "", search_focus: str = "internet") -> list[dict]:
assert self.finished, "already searching"
self._start_interaction()
ws_message: str = f"{self.base + self.n}" + dumps([
"list_autosuggest",
query,
{
"has_attachment": False,
"search_focus": search_focus,
"source": "default",
"version": "2.1"
}
])
self.ws.send(ws_message)
while not self.finished or len(self.queue) != 0:
if len(self.queue) != 0:
return self.queue.pop(0)
def close(self) -> None:
self.ws.close()
if self.email:
with open(".perplexity_session", "r") as f:
perplexity_session: dict = loads(f.read())
perplexity_session[self.email] = self.session.cookies.get_dict()
with open(".perplexity_session", "w") as f:
f.write(dumps(perplexity_session))
|