gpt4free/g4f/Provider/Phind.py

139 lines
5.2 KiB
Python
Raw Normal View History

from __future__ import annotations
2024-02-22 11:54:50 +03:00
import re
import json
from urllib import parse
2023-11-22 17:22:36 +03:00
from datetime import datetime
2023-11-22 17:22:36 +03:00
from ..typing import AsyncResult, Messages
from .base_provider import AsyncGeneratorProvider
from ..requests import StreamSession
2023-11-22 17:22:36 +03:00
class Phind(AsyncGeneratorProvider):
url = "https://www.phind.com"
working = True
supports_stream = True
2023-11-22 17:22:36 +03:00
supports_message_history = True
@classmethod
2023-11-22 17:22:36 +03:00
async def create_async_generator(
cls,
model: str,
2023-10-10 10:49:29 +03:00
messages: Messages,
proxy: str = None,
2023-10-09 11:22:17 +03:00
timeout: int = 120,
2023-11-22 17:22:36 +03:00
creative_mode: bool = False,
**kwargs
2023-11-22 17:22:36 +03:00
) -> AsyncResult:
headers = {
"Accept": "*/*",
"Origin": cls.url,
"Referer": f"{cls.url}/search",
"Sec-Fetch-Dest": "empty",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "same-origin",
}
2023-11-22 17:22:36 +03:00
async with StreamSession(
2024-02-22 11:54:50 +03:00
headers=headers,
impersonate="chrome",
2023-11-22 17:22:36 +03:00
proxies={"https": proxy},
timeout=timeout
) as session:
2024-02-22 11:54:50 +03:00
url = "https://www.phind.com/search?home=true"
async with session.get(url) as response:
text = await response.text()
match = re.search(r'<script id="__NEXT_DATA__" type="application/json">(?P<json>[\S\s]+?)</script>', text)
data = json.loads(match.group("json"))
challenge_seeds = data["props"]["pageProps"]["challengeSeeds"]
2023-11-22 17:22:36 +03:00
prompt = messages[-1]["content"]
data = {
"question": prompt,
"question_history": [
2023-11-22 17:22:36 +03:00
message["content"] for message in messages[:-1] if message["role"] == "user"
],
"answer_history": [
2023-11-22 17:22:36 +03:00
message["content"] for message in messages if message["role"] == "assistant"
],
"webResults": [],
"options": {
"date": datetime.now().strftime("%d.%m.%Y"),
"language": "en-US",
"detailed": True,
"anonUserId": "",
2024-02-22 11:54:50 +03:00
"answerModel": "GPT-4" if model.startswith("gpt-4") else "Phind-34B",
2023-11-22 17:22:36 +03:00
"creativeMode": creative_mode,
"customLinks": []
},
2024-01-21 21:58:39 +03:00
"context": "\n".join([message["content"] for message in messages if message["role"] == "system"]),
2023-11-22 17:22:36 +03:00
}
2024-02-22 11:54:50 +03:00
data["challenge"] = generate_challenge(data, **challenge_seeds)
async with session.post(f"https://https.api.phind.com/infer/", headers=headers, json=data) as response:
2023-11-22 17:22:36 +03:00
new_line = False
async for line in response.iter_lines():
if line.startswith(b"data: "):
chunk = line[6:]
if chunk.startswith(b'<PHIND_DONE/>'):
break
if chunk.startswith(b'<PHIND_BACKEND_ERROR>'):
raise RuntimeError(f"Response: {chunk.decode()}")
if chunk.startswith(b'<PHIND_WEBRESULTS>') or chunk.startswith(b'<PHIND_FOLLOWUP>'):
pass
elif chunk.startswith(b"<PHIND_METADATA>") or chunk.startswith(b"<PHIND_INDICATOR>"):
2023-11-22 17:22:36 +03:00
pass
elif chunk.startswith(b"<PHIND_SPAN_BEGIN>") or chunk.startswith(b"<PHIND_SPAN_END>"):
pass
2023-11-22 17:22:36 +03:00
elif chunk:
yield chunk.decode()
elif new_line:
yield "\n"
new_line = False
else:
2023-12-27 00:41:19 +03:00
new_line = True
def deterministic_stringify(obj):
def handle_value(value):
if isinstance(value, (dict, list)):
if isinstance(value, list):
return '[' + ','.join(sorted(map(handle_value, value))) + ']'
else: # It's a dict
return '{' + deterministic_stringify(value) + '}'
elif isinstance(value, bool):
return 'true' if value else 'false'
elif isinstance(value, (int, float)):
return format(value, '.8f').rstrip('0').rstrip('.')
elif isinstance(value, str):
return f'"{value}"'
else:
return 'null'
items = sorted(obj.items(), key=lambda x: x[0])
return ','.join([f'{k}:{handle_value(v)}' for k, v in items if handle_value(v) is not None])
2024-02-22 11:54:50 +03:00
def prng_general(seed, multiplier, addend, modulus):
a = seed * multiplier + addend
if a < 0:
return ((a%modulus)-modulus)/modulus
else:
return a%modulus/modulus
def generate_challenge_seed(l):
I = deterministic_stringify(l)
d = parse.quote(I, safe='')
return simple_hash(d)
def simple_hash(s):
d = 0
for char in s:
if len(char) > 1 or ord(char) >= 256:
continue
d = ((d << 5) - d + ord(char[0])) & 0xFFFFFFFF
if d > 0x7FFFFFFF: # 2147483647
d -= 0x100000000 # Subtract 2**32
return d
2024-02-22 11:54:50 +03:00
def generate_challenge(obj, **kwargs):
return prng_general(
seed=generate_challenge_seed(obj),
**kwargs
)