mirror of
https://github.com/HIllya51/LunaTranslator.git
synced 2024-12-28 08:04:13 +08:00
...
This commit is contained in:
parent
ac15a09471
commit
5041de78b8
@ -917,11 +917,22 @@ def checkv1(api_url: str):
|
||||
return api_url + "/v1"
|
||||
|
||||
|
||||
def urlpathjoin(*argc):
|
||||
urlx = []
|
||||
for i, u in enumerate(argc):
|
||||
if u.startswith("/") and i != 0:
|
||||
u = u[1:]
|
||||
if u.endswith("/") and i != len(argc) - 1:
|
||||
u = u[:-1]
|
||||
urlx.append(u)
|
||||
return "/".join(urlx)
|
||||
|
||||
|
||||
def createurl(url: str):
|
||||
if url.endswith("/chat/completions"):
|
||||
pass
|
||||
else:
|
||||
url = checkv1(url) + "/chat/completions"
|
||||
url = urlpathjoin(checkv1(url), "/chat/completions")
|
||||
return url
|
||||
|
||||
|
||||
|
@ -43,7 +43,7 @@ class OCR(baseocr):
|
||||
]
|
||||
return {"box": box, "text": text, "isocrtranslate": True}
|
||||
except:
|
||||
raise Exception(response.text)
|
||||
raise Exception(response.maybejson)
|
||||
|
||||
def ocr_ts2(self, imagebinary):
|
||||
self.checkempty(["app_id", "app_key"])
|
||||
@ -103,7 +103,7 @@ class OCR(baseocr):
|
||||
]
|
||||
return {"box": box, "text": text, "isocrtranslate": True}
|
||||
except:
|
||||
raise Exception(response.text)
|
||||
raise Exception(response.maybejson)
|
||||
|
||||
@property
|
||||
def srclangx(self):
|
||||
@ -154,12 +154,12 @@ class OCR(baseocr):
|
||||
"client_id": API_KEY,
|
||||
"client_secret": SECRET_KEY,
|
||||
}
|
||||
js = self.proxysession.post(url, params=params).json()
|
||||
resp = self.proxysession.post(url, params=params)
|
||||
|
||||
try:
|
||||
return js["access_token"]
|
||||
return resp.json()["access_token"]
|
||||
except:
|
||||
raise Exception(js)
|
||||
raise Exception(resp.maybejson)
|
||||
|
||||
def getaccess(self):
|
||||
self.checkempty(["API Key", "Secret Key"])
|
||||
@ -236,4 +236,4 @@ class OCR(baseocr):
|
||||
]
|
||||
return {"box": boxs, "text": texts}
|
||||
except:
|
||||
raise Exception(response.text)
|
||||
raise Exception(response.maybejson)
|
||||
|
@ -1,21 +1,25 @@
|
||||
from ocrengines.baseocrclass import baseocr
|
||||
import base64, requests
|
||||
from myutils.utils import createurl, createenglishlangmap
|
||||
from myutils.utils import createurl, createenglishlangmap, urlpathjoin
|
||||
from myutils.proxy import getproxy
|
||||
|
||||
|
||||
def list_models(typename, regist):
|
||||
js = requests.get(
|
||||
createurl(regist["apiurl"]().strip())[: -len("/chat/completions")] + "/models",
|
||||
headers={"Authorization": "Bearer " + regist["SECRET_KEY"]().split("|")[0].strip()},
|
||||
resp = requests.get(
|
||||
urlpathjoin(
|
||||
createurl(regist["apiurl"]().strip())[: -len("chat/completions")],
|
||||
"models",
|
||||
),
|
||||
headers={
|
||||
"Authorization": "Bearer " + regist["SECRET_KEY"]().split("|")[0].strip()
|
||||
},
|
||||
proxies=getproxy(("ocr", typename)),
|
||||
timeout=10,
|
||||
).json()
|
||||
|
||||
)
|
||||
try:
|
||||
return sorted([_["id"] for _ in js["data"]])
|
||||
return sorted([_["id"] for _ in resp.json()["data"]])
|
||||
except:
|
||||
raise Exception(js)
|
||||
raise Exception(resp.maybejson)
|
||||
|
||||
|
||||
class OCR(baseocr):
|
||||
@ -79,7 +83,7 @@ class OCR(baseocr):
|
||||
)
|
||||
return message
|
||||
except:
|
||||
raise Exception(response.text)
|
||||
raise Exception(response.maybejson)
|
||||
|
||||
def createurl(self):
|
||||
return createurl(self.config["apiurl"])
|
||||
|
@ -34,4 +34,4 @@ class OCR(baseocr):
|
||||
try:
|
||||
return response.json()["data"]
|
||||
except:
|
||||
raise Exception(response.text)
|
||||
raise Exception(response.maybejson)
|
||||
|
@ -20,7 +20,7 @@ class OCR(baseocr):
|
||||
try:
|
||||
token = res.json()["tenant_access_token"]
|
||||
except:
|
||||
raise Exception(res.json())
|
||||
raise Exception(res.maybejson)
|
||||
self.tokens[(app_id, app_secret)] = token
|
||||
return self.tokens[(app_id, app_secret)]
|
||||
|
||||
@ -40,4 +40,4 @@ class OCR(baseocr):
|
||||
try:
|
||||
return res.json()["data"]["text_list"]
|
||||
except:
|
||||
raise Exception(res.text)
|
||||
raise Exception(res.maybejson)
|
||||
|
@ -1,21 +1,21 @@
|
||||
import base64
|
||||
import requests
|
||||
from ocrengines.baseocrclass import baseocr
|
||||
from myutils.utils import createenglishlangmap
|
||||
from myutils.utils import createenglishlangmap, urlpathjoin
|
||||
from myutils.proxy import getproxy
|
||||
|
||||
|
||||
def list_models(typename, regist):
|
||||
js = requests.get(
|
||||
"https://generativelanguage.googleapis.com/v1beta/models",
|
||||
resp = requests.get(
|
||||
urlpathjoin(regist["BASE_URL"]().strip(), "v1beta/models"),
|
||||
params={"key": regist["key"]().split("|")[0].strip()},
|
||||
proxies=getproxy(("ocr", typename)),
|
||||
timeout=10,
|
||||
).json()
|
||||
)
|
||||
try:
|
||||
models = js["models"]
|
||||
models = resp.json()["models"]
|
||||
except:
|
||||
raise Exception(js)
|
||||
raise Exception(resp.maybejson)
|
||||
mm = []
|
||||
for m in models:
|
||||
name: str = m["name"]
|
||||
@ -34,10 +34,9 @@ class OCR(baseocr):
|
||||
|
||||
def ocr(self, imagebinary):
|
||||
self.checkempty(["key"])
|
||||
self.checkempty(["url"])
|
||||
self.checkempty(["BASE_URL"])
|
||||
self.checkempty(["model"])
|
||||
api_key = self.config["key"]
|
||||
url = self.config["url"]
|
||||
model = self.config["model"]
|
||||
image_data = base64.b64encode(imagebinary).decode("utf-8")
|
||||
|
||||
@ -59,15 +58,21 @@ class OCR(baseocr):
|
||||
# Set up the request headers and URL
|
||||
headers = {"Content-Type": "application/json"}
|
||||
# by default https://generativelanguage.googleapis.com/v1
|
||||
url = f"{url}/models/{model}:generateContent?key={api_key}"
|
||||
|
||||
# Send the request
|
||||
response = requests.post(url, headers=headers, json=payload, proxies=self.proxy)
|
||||
response = requests.post(
|
||||
urlpathjoin(
|
||||
self.config["BASE_URL"],
|
||||
f"v1beta/models/{model}:generateContent?key={api_key}",
|
||||
),
|
||||
headers=headers,
|
||||
json=payload,
|
||||
proxies=self.proxy,
|
||||
)
|
||||
try:
|
||||
# Handle the response
|
||||
if response.status_code == 200:
|
||||
return response.json()["candidates"][0]["content"]["parts"][0]["text"]
|
||||
else:
|
||||
raise Exception(response.text)
|
||||
raise Exception(response.maybejson)
|
||||
except Exception as e:
|
||||
raise Exception(response.text) from e
|
||||
raise Exception(response.maybejson) from e
|
||||
|
@ -42,4 +42,4 @@ class OCR(baseocr):
|
||||
)
|
||||
return {"box": boxs, "text": texts}
|
||||
except:
|
||||
raise Exception(response.text)
|
||||
raise Exception(response.maybejson)
|
||||
|
@ -20,4 +20,4 @@ class OCR(baseocr):
|
||||
try:
|
||||
return response.json()["text"]
|
||||
except Exception as e:
|
||||
raise Exception(response.text) from e
|
||||
raise Exception(response.maybejson) from e
|
||||
|
@ -51,7 +51,6 @@ class OCR(baseocr):
|
||||
response = self.proxysession.post(
|
||||
"https://" + base + "/parse/image", headers=headers, data=data
|
||||
)
|
||||
# print(response.text)
|
||||
try:
|
||||
_ = response.json()["ParsedResults"][0]["ParsedText"]
|
||||
boxs = []
|
||||
@ -71,4 +70,4 @@ class OCR(baseocr):
|
||||
]
|
||||
return {"box": boxs, "text": texts}
|
||||
except:
|
||||
raise Exception(response.text)
|
||||
raise Exception(response.maybejson)
|
||||
|
@ -144,7 +144,7 @@ class OCR(baseocr):
|
||||
]
|
||||
return {"box": boxs, "text": texts, "isocrtranslate": True}
|
||||
except:
|
||||
raise Exception(r.json())
|
||||
raise Exception(r.maybejson)
|
||||
|
||||
def langmap(self):
|
||||
# https://cloud.tencent.com/document/product/866/33526
|
||||
@ -190,7 +190,6 @@ class OCR(baseocr):
|
||||
r = self.proxysession.get(
|
||||
url="https://ocr.tencentcloudapi.com/", params=req_para, timeout=10
|
||||
)
|
||||
# print(r.text)
|
||||
|
||||
try:
|
||||
boxs = [
|
||||
@ -209,7 +208,7 @@ class OCR(baseocr):
|
||||
texts = [_["DetectedText"] for _ in r.json()["Response"]["TextDetections"]]
|
||||
return {"box": boxs, "text": texts}
|
||||
except:
|
||||
raise Exception(r.text)
|
||||
raise Exception(r.maybejson)
|
||||
|
||||
def ocr(self, imagebinary):
|
||||
interfacetype = self.config["interface"]
|
||||
|
@ -442,7 +442,7 @@ class Service(object):
|
||||
if resp.status_code == 200:
|
||||
return resp.text
|
||||
else:
|
||||
raise Exception(resp.text)
|
||||
raise Exception(resp.maybejson)
|
||||
|
||||
def prepare_request(self, api_info, params, doseq=0):
|
||||
for key in params:
|
||||
|
@ -124,14 +124,11 @@ class OCR(baseocr):
|
||||
request_url, data=json.dumps(body), headers=headers
|
||||
)
|
||||
|
||||
re = response.content.decode("utf8")
|
||||
str_result = json.loads(re)
|
||||
# print("\nresponse-content:", re)
|
||||
try:
|
||||
renew_text = str_result["payload"]["ocr_output_text"]["text"]
|
||||
renew_text = response.json()["payload"]["ocr_output_text"]["text"]
|
||||
finalResult = json.loads(str(base64.b64decode(renew_text), "utf-8"))
|
||||
except:
|
||||
raise Exception(str_result)
|
||||
raise Exception(response.maybejson)
|
||||
try:
|
||||
res = finalResult["pages"][0]
|
||||
if "lines" not in res:
|
||||
|
@ -47,7 +47,7 @@ class OCR(baseocr):
|
||||
"text": [l["words"] for l in response.json()["lines"]],
|
||||
}
|
||||
except:
|
||||
raise Exception(response.text)
|
||||
raise Exception(response.maybejson)
|
||||
|
||||
def ocrapi(self, imagebinary):
|
||||
def truncate(q):
|
||||
@ -93,7 +93,7 @@ class OCR(baseocr):
|
||||
"text": [l["text"] for l in _],
|
||||
}
|
||||
except:
|
||||
raise Exception(response.text)
|
||||
raise Exception(response.maybejson)
|
||||
|
||||
def freetest_ts(self, imagebinary):
|
||||
|
||||
@ -129,7 +129,7 @@ class OCR(baseocr):
|
||||
"isocrtranslate": True,
|
||||
}
|
||||
except:
|
||||
raise Exception(response.text)
|
||||
raise Exception(response.maybejson)
|
||||
|
||||
def ocrapi_ts(self, imagebinary):
|
||||
|
||||
@ -237,7 +237,7 @@ class OCR(baseocr):
|
||||
]
|
||||
return {"box": box, "text": text, "isocrtranslate": True}
|
||||
except:
|
||||
raise Exception(response.text)
|
||||
raise Exception(response.maybejson)
|
||||
|
||||
def ocr(self, imagebinary):
|
||||
interfacetype = self.config["interface"]
|
||||
|
@ -108,6 +108,13 @@ class ResponseBase:
|
||||
m = re.search(r"charset=([\w-]+)", content_type)
|
||||
charset = m.group(1) if m else "utf-8"
|
||||
return charset
|
||||
|
||||
@property
|
||||
def maybejson(self):
|
||||
try:
|
||||
return self.json()
|
||||
except:
|
||||
return self.text
|
||||
|
||||
def json(self):
|
||||
return json.loads(self.text)
|
||||
|
@ -79,5 +79,5 @@ class TS(basetrans):
|
||||
try:
|
||||
trans = data["data"]["translateText"]
|
||||
except:
|
||||
raise Exception(r.text)
|
||||
raise Exception(r.maybejson)
|
||||
return html.unescape(trans)
|
||||
|
@ -58,4 +58,4 @@ class TS(basetrans):
|
||||
response = request.json()
|
||||
return response["Data"]["Translated"]
|
||||
except:
|
||||
raise Exception(request.text)
|
||||
raise Exception(request.maybejson)
|
||||
|
@ -37,4 +37,4 @@ class TS(basetrans):
|
||||
try:
|
||||
return response[0]["translations"][0]["text"]
|
||||
except:
|
||||
raise Exception(request.text)
|
||||
raise Exception(request.maybejson)
|
||||
|
@ -111,8 +111,6 @@ class BaiduV1(Tse):
|
||||
timeout = kwargs.get("timeout", None)
|
||||
proxies = kwargs.get("proxies", None)
|
||||
sleep_seconds = kwargs.get("sleep_seconds", 0)
|
||||
if_print_warning = kwargs.get("if_print_warning", True)
|
||||
is_detail_result = kwargs.get("is_detail_result", False)
|
||||
update_session_after_freq = kwargs.get(
|
||||
"update_session_after_freq", self.default_session_freq
|
||||
)
|
||||
@ -120,10 +118,6 @@ class BaiduV1(Tse):
|
||||
"update_session_after_seconds", self.default_session_seconds
|
||||
)
|
||||
|
||||
not_update_cond_freq = 1 if self.query_count < update_session_after_freq else 0
|
||||
not_update_cond_time = (
|
||||
1 if time.time() - self.begin_time < update_session_after_seconds else 0
|
||||
)
|
||||
if not (self.session):
|
||||
self.session = requests.Session()
|
||||
_ = self.session.get(
|
||||
@ -154,17 +148,12 @@ class BaiduV1(Tse):
|
||||
proxies=proxies,
|
||||
)
|
||||
r.raise_for_status()
|
||||
data = r.json()
|
||||
time.sleep(sleep_seconds)
|
||||
self.query_count += 1
|
||||
try:
|
||||
return (
|
||||
data
|
||||
if is_detail_result
|
||||
else "\n".join([item["dst"] for item in data["data"]])
|
||||
)
|
||||
return "\n".join([item["dst"] for item in r.json()["data"]])
|
||||
except:
|
||||
raise Exception(data)
|
||||
raise Exception(r.maybejson)
|
||||
|
||||
|
||||
class TS(basetrans):
|
||||
|
@ -69,7 +69,7 @@ class TS(basetrans):
|
||||
try:
|
||||
return "\n".join([_["dst"] for _ in r.json()["result"]["trans_result"]])
|
||||
except:
|
||||
raise Exception(r.text)
|
||||
raise Exception(r.maybejson)
|
||||
|
||||
def translate_fy(self, q):
|
||||
self.checkempty(["APP ID", "密钥"])
|
||||
@ -94,4 +94,4 @@ class TS(basetrans):
|
||||
return "\n".join([_["dst"] for _ in res.json()["trans_result"]])
|
||||
|
||||
except:
|
||||
raise Exception(res.text)
|
||||
raise Exception(res.maybejson)
|
||||
|
@ -52,7 +52,7 @@ class TS(basetrans):
|
||||
try:
|
||||
message = response.json()["result"].replace("\n\n", "\n").strip()
|
||||
except:
|
||||
raise Exception(response.text)
|
||||
raise Exception(response.maybejson)
|
||||
yield message
|
||||
self.context.append({"role": "user", "content": query})
|
||||
self.context.append({"role": "assistant", "content": message})
|
||||
|
@ -190,7 +190,6 @@ class Bing(Tse):
|
||||
)
|
||||
r.raise_for_status()
|
||||
data = r.json()
|
||||
print(r.text)
|
||||
time.sleep(sleep_seconds)
|
||||
self.query_count += 1
|
||||
return data[0] if is_detail_result else data[0]["translations"][0]["text"]
|
||||
|
@ -121,4 +121,4 @@ class TS(basetrans):
|
||||
try:
|
||||
return decrypt(response.json()["target"])
|
||||
except:
|
||||
raise Exception(response.json())
|
||||
raise Exception(response.maybejson)
|
||||
|
@ -26,6 +26,6 @@ class TS(basetrans):
|
||||
"POST", url, data=json.dumps(payload), headers=headers
|
||||
)
|
||||
try:
|
||||
return json.loads(response.text)["target"]
|
||||
return response.json()["target"]
|
||||
except:
|
||||
raise Exception(response.text)
|
||||
raise Exception(response.maybejson)
|
||||
|
@ -1,7 +1,7 @@
|
||||
from traceback import print_exc
|
||||
import json
|
||||
from translator.basetranslator import basetrans
|
||||
from myutils.utils import createenglishlangmap, checkv1
|
||||
from myutils.utils import createenglishlangmap, checkv1, urlpathjoin
|
||||
|
||||
|
||||
class TS(basetrans):
|
||||
@ -24,7 +24,9 @@ class TS(basetrans):
|
||||
temperature = self.config["Temperature"]
|
||||
|
||||
message = []
|
||||
self._gpt_common_parse_context(message, self.context, self.config["附带上下文个数"])
|
||||
self._gpt_common_parse_context(
|
||||
message, self.context, self.config["附带上下文个数"]
|
||||
)
|
||||
message.append({"role": "user", "content": query})
|
||||
prefill = self._gptlike_create_prefill("prefill_use", "prefill")
|
||||
if prefill:
|
||||
@ -46,7 +48,7 @@ class TS(basetrans):
|
||||
stream=usingstream,
|
||||
)
|
||||
response = self.proxysession.post(
|
||||
checkv1(self.config["BASE_URL"]) + "/messages",
|
||||
urlpathjoin(checkv1(self.config["BASE_URL"]) + "messages"),
|
||||
headers=headers,
|
||||
json=data,
|
||||
stream=usingstream,
|
||||
@ -83,7 +85,7 @@ class TS(basetrans):
|
||||
response.json()["content"][0]["text"].replace("\n\n", "\n").strip()
|
||||
)
|
||||
except:
|
||||
raise Exception(response.text)
|
||||
raise Exception(response.maybejson)
|
||||
yield message
|
||||
self.context.append({"role": "user", "content": query})
|
||||
self.context.append({"role": "assistant", "content": message})
|
||||
|
@ -116,7 +116,7 @@ class TS(basetrans):
|
||||
try:
|
||||
message = response.json()["text"]
|
||||
except:
|
||||
raise Exception(response.text)
|
||||
raise Exception(response.maybejson)
|
||||
yield message
|
||||
self.context.append({"role": "USER", "message": query})
|
||||
self.context.append({"role": "CHATBOT", "message": message})
|
||||
|
@ -87,7 +87,7 @@ class TS(basetrans):
|
||||
try:
|
||||
return response.json()["data"]
|
||||
except:
|
||||
raise Exception(response.text)
|
||||
raise Exception(response.maybejson)
|
||||
|
||||
def translate_deeplx_internal(self, translateText):
|
||||
# Preparing the request data for the DeepL API
|
||||
|
@ -48,4 +48,4 @@ class TS(basetrans):
|
||||
try:
|
||||
return response.json()["translations"][0]["text"]
|
||||
except:
|
||||
raise Exception(response.text)
|
||||
raise Exception(response.maybejson)
|
||||
|
@ -22,7 +22,7 @@ class TS(basetrans):
|
||||
try:
|
||||
token = res.json()["tenant_access_token"]
|
||||
except:
|
||||
raise Exception(res.json())
|
||||
raise Exception(res.maybejson)
|
||||
self.tokens[(app_id, app_secret)] = token
|
||||
return self.tokens[(app_id, app_secret)]
|
||||
|
||||
@ -45,4 +45,4 @@ class TS(basetrans):
|
||||
try:
|
||||
return res.json()["data"]["text"]
|
||||
except:
|
||||
raise Exception(res.text)
|
||||
raise Exception(res.maybejson)
|
||||
|
@ -1,5 +1,5 @@
|
||||
from translator.basetranslator import basetrans
|
||||
from myutils.utils import createenglishlangmap
|
||||
from myutils.utils import createenglishlangmap, urlpathjoin
|
||||
import json, requests
|
||||
from myutils.proxy import getproxy
|
||||
|
||||
@ -61,7 +61,10 @@ class TS(basetrans):
|
||||
usingstream = self.config["usingstream"]
|
||||
payload = {**contents, **safety, **sys_message, **gen_config}
|
||||
res = self.proxysession.post(
|
||||
f"https://generativelanguage.googleapis.com/v1beta/models/{model}:{['generateContent','streamGenerateContent'][usingstream]}",
|
||||
urlpathjoin(
|
||||
self.config["BASE_URL"],
|
||||
f"v1beta/models/{model}:{['generateContent','streamGenerateContent'][usingstream]}",
|
||||
),
|
||||
params={"key": self.multiapikeycurrent["SECRET_KEY"]},
|
||||
json=payload,
|
||||
stream=usingstream,
|
||||
@ -80,7 +83,7 @@ class TS(basetrans):
|
||||
try:
|
||||
line = res.json()["candidates"][0]["content"]["parts"][0]["text"]
|
||||
except:
|
||||
raise Exception(res.text)
|
||||
raise Exception(res.maybejson)
|
||||
yield line
|
||||
self.context.append({"role": "user", "parts": [{"text": query}]})
|
||||
self.context.append({"role": "model", "parts": [{"text": line}]})
|
||||
@ -88,7 +91,7 @@ class TS(basetrans):
|
||||
|
||||
def list_models(typename, regist):
|
||||
js = requests.get(
|
||||
"https://generativelanguage.googleapis.com/v1beta/models",
|
||||
urlpathjoin(regist["BASE_URL"]().strip(), "v1beta/models"),
|
||||
params={"key": regist["SECRET_KEY"]().split("|")[0].strip()},
|
||||
proxies=getproxy(("fanyi", typename)),
|
||||
timeout=10,
|
||||
|
@ -77,8 +77,6 @@ class TS(basetrans):
|
||||
headers=headers,
|
||||
data=freq,
|
||||
)
|
||||
# good=response.text.split('\n')[3]
|
||||
# print(response.text)
|
||||
json_data = json.loads(response.text[6:])
|
||||
data = json.loads(json_data[0][2])
|
||||
return " ".join([x[0] for x in (data[1][0][0][5] or data[1][0])])
|
||||
|
@ -23,4 +23,4 @@ class TS(basetrans):
|
||||
try:
|
||||
return response.json()["data"]["translations"][0]["translatedText"]
|
||||
except:
|
||||
raise Exception(response.text)
|
||||
raise Exception(response.maybejson)
|
||||
|
@ -1,25 +1,25 @@
|
||||
from translator.basetranslator import basetrans
|
||||
import json, requests
|
||||
from traceback import print_exc
|
||||
from myutils.utils import createurl, createenglishlangmap
|
||||
from myutils.utils import createurl, createenglishlangmap, urlpathjoin
|
||||
from myutils.proxy import getproxy
|
||||
|
||||
|
||||
def list_models(typename, regist):
|
||||
js = requests.get(
|
||||
createurl(regist["API接口地址"]().strip())[: -len("/chat/completions")]
|
||||
+ "/models",
|
||||
resp = requests.get(
|
||||
urlpathjoin(
|
||||
createurl(regist["API接口地址"]().strip())[: -len("chat/completions")],
|
||||
"models",
|
||||
),
|
||||
headers={
|
||||
"Authorization": "Bearer " + regist["SECRET_KEY"]().split("|")[0].strip()
|
||||
},
|
||||
proxies=getproxy(("fanyi", typename)),
|
||||
timeout=10,
|
||||
).json()
|
||||
|
||||
)
|
||||
try:
|
||||
return sorted([_["id"] for _ in js["data"]])
|
||||
return sorted([_["id"] for _ in resp.json()["data"]])
|
||||
except:
|
||||
raise Exception(js)
|
||||
raise Exception(resp.maybejson)
|
||||
|
||||
|
||||
class gptcommon(basetrans):
|
||||
@ -74,7 +74,7 @@ class gptcommon(basetrans):
|
||||
if not response.headers["Content-Type"].startswith("text/event-stream"):
|
||||
# application/json
|
||||
# text/html
|
||||
raise Exception(response.text)
|
||||
raise Exception(response.maybejson)
|
||||
for chunk in response.iter_lines():
|
||||
response_data: str = chunk.decode("utf-8").strip()
|
||||
if not response_data.startswith("data: "):
|
||||
@ -105,7 +105,7 @@ class gptcommon(basetrans):
|
||||
.strip()
|
||||
)
|
||||
except:
|
||||
raise Exception(response.text)
|
||||
raise Exception(response.maybejson)
|
||||
yield message
|
||||
self.context.append({"role": "user", "content": query})
|
||||
self.context.append({"role": "assistant", "content": message})
|
||||
@ -116,7 +116,9 @@ class gptcommon(basetrans):
|
||||
)
|
||||
sysprompt = self._gptlike_createsys("使用自定义promt", "自定义promt")
|
||||
message = [{"role": "system", "content": sysprompt}]
|
||||
self._gpt_common_parse_context(message, self.context, self.config["附带上下文个数"])
|
||||
self._gpt_common_parse_context(
|
||||
message, self.context, self.config["附带上下文个数"]
|
||||
)
|
||||
message.append({"role": "user", "content": query})
|
||||
prefill = self._gptlike_create_prefill("prefill_use", "prefill")
|
||||
if prefill:
|
||||
|
@ -37,4 +37,4 @@ class TS(basetrans):
|
||||
try:
|
||||
return response.json()["translation"]
|
||||
except:
|
||||
raise Exception(response.text)
|
||||
raise Exception(response.maybejson)
|
||||
|
@ -336,7 +336,7 @@ class Service(object):
|
||||
if resp.status_code == 200:
|
||||
return json.dumps(resp.json())
|
||||
else:
|
||||
raise Exception(resp.text)
|
||||
raise Exception(resp.maybejson)
|
||||
|
||||
def prepare_request(self, api_info, params, doseq=0):
|
||||
for key in params:
|
||||
|
@ -314,7 +314,7 @@ class TS(basetrans):
|
||||
try:
|
||||
project_id = response.json()["projects"][0]["id"]
|
||||
except:
|
||||
raise Exception(response.json())
|
||||
raise Exception(response.maybejson)
|
||||
self.cacheproject[(end, ak, sk)] = project_id
|
||||
project_id = self.cacheproject.get((end, ak, sk))
|
||||
url = f"https://{end}/v1/{project_id}/machine-translation/text-translation"
|
||||
|
@ -20,4 +20,4 @@ class TS(basetrans):
|
||||
translation = result["translations"][0]["translation"]
|
||||
return translation
|
||||
except Exception as e:
|
||||
raise Exception(response.text)
|
||||
raise Exception(response.maybejson)
|
||||
|
@ -143,7 +143,7 @@ class Itranslate(Tse):
|
||||
try:
|
||||
return r.json()["target"]["text"]
|
||||
except:
|
||||
raise Exception(r.text)
|
||||
raise Exception(r.maybejson)
|
||||
|
||||
|
||||
from traceback import print_exc
|
||||
|
@ -1,6 +1,7 @@
|
||||
from translator.basetranslator import basetrans
|
||||
import requests
|
||||
import json, zhconv
|
||||
from myutils.utils import urlpathjoin
|
||||
|
||||
# OpenAI
|
||||
# from openai import OpenAI
|
||||
@ -140,14 +141,16 @@ class TS(basetrans):
|
||||
stream=False,
|
||||
)
|
||||
try:
|
||||
output = self.session.post(self.api_url + "/chat/completions", json=data)
|
||||
output = self.session.post(
|
||||
urlpathjoin(self.api_url, "chat/completions"), json=data
|
||||
)
|
||||
|
||||
except requests.RequestException as e:
|
||||
raise ValueError(f"连接到Sakura API超时:{self.api_url}")
|
||||
try:
|
||||
yield output.json()
|
||||
except:
|
||||
raise Exception(output.text)
|
||||
raise Exception(output.maybejson)
|
||||
|
||||
def send_request_stream(self, messages, is_test=False, **kwargs):
|
||||
extra_query = {
|
||||
@ -173,14 +176,14 @@ class TS(basetrans):
|
||||
)
|
||||
try:
|
||||
output = self.session.post(
|
||||
self.api_url + "/chat/completions",
|
||||
urlpathjoin(self.api_url, "chat/completions"),
|
||||
json=data,
|
||||
stream=True,
|
||||
)
|
||||
except requests.RequestException:
|
||||
raise ValueError(f"连接到Sakura API超时:{self.api_url}")
|
||||
if not output.headers["Content-Type"].startswith("text/event-stream"):
|
||||
raise Exception(output.text)
|
||||
raise Exception(output.maybejson)
|
||||
for chunk in output.iter_lines():
|
||||
response_data: str = chunk.decode("utf-8").strip()
|
||||
if not response_data.startswith("data: "):
|
||||
|
@ -1,6 +1,4 @@
|
||||
import requests, os
|
||||
from translator.basetranslator import basetrans
|
||||
from myutils.subproc import subproc_w, autoproc
|
||||
|
||||
|
||||
class TS(basetrans):
|
||||
@ -15,4 +13,4 @@ class TS(basetrans):
|
||||
try:
|
||||
return response.json()
|
||||
except:
|
||||
raise Exception(response.text)
|
||||
raise Exception(response.maybejson)
|
||||
|
@ -75,4 +75,4 @@ class TS(basetrans):
|
||||
try:
|
||||
return ret.json()["Response"]["TargetText"]
|
||||
except:
|
||||
raise Exception(ret.text)
|
||||
raise Exception(ret.maybejson)
|
||||
|
@ -146,7 +146,7 @@ class TS(basetrans):
|
||||
"Content"
|
||||
]
|
||||
except:
|
||||
raise Exception(response.text)
|
||||
raise Exception(response.maybejson)
|
||||
yield message
|
||||
self.context.append({"Role": "user", "Content": query})
|
||||
self.context.append({"Role": "assistant", "Content": message})
|
||||
|
@ -38,4 +38,4 @@ class TS(basetrans):
|
||||
try:
|
||||
return response.json()["tgt_text"]
|
||||
except:
|
||||
raise Exception(response.text)
|
||||
raise Exception(response.maybejson)
|
||||
|
@ -24,4 +24,4 @@ class TS(basetrans):
|
||||
try:
|
||||
return response.json()["text"][0]
|
||||
except:
|
||||
raise Exception(response.text)
|
||||
raise Exception(response.maybejson)
|
||||
|
@ -21,4 +21,4 @@ class TS(basetrans):
|
||||
try:
|
||||
return response.json()["text"][0]
|
||||
except:
|
||||
raise Exception(response.text)
|
||||
raise Exception(response.maybejson)
|
||||
|
@ -105,7 +105,4 @@ class TS(basetrans):
|
||||
|
||||
return res
|
||||
except:
|
||||
raise Exception(response.text)
|
||||
|
||||
def show(self, res):
|
||||
print("有道", "\033[0;33;47m", res, "\033[0m", flush=True)
|
||||
raise Exception(response.maybejson)
|
||||
|
@ -58,4 +58,4 @@ class TS(basetrans):
|
||||
|
||||
return js
|
||||
except:
|
||||
raise Exception(response.text)
|
||||
raise Exception(response.maybejson)
|
||||
|
@ -45,4 +45,4 @@ class TS(basetrans):
|
||||
try:
|
||||
return r.json()["translation"][0]
|
||||
except:
|
||||
raise Exception(r.text)
|
||||
raise Exception(r.maybejson)
|
||||
|
@ -43,81 +43,34 @@ class TS(basetrans):
|
||||
}
|
||||
|
||||
mysticTime, sign = self.signx()
|
||||
if v == 10:
|
||||
param = {
|
||||
"keyfrom": "deskdict.main",
|
||||
"client": "deskdict",
|
||||
"from": self.srclang,
|
||||
"to": self.tgtlang,
|
||||
"keyid": "deskdict",
|
||||
"mysticTime": mysticTime,
|
||||
"pointParam": "client,product,mysticTime", # 只要不改pointParam,client,product,mysticTime,就不需要重新签名
|
||||
"sign": sign,
|
||||
"domain": "0",
|
||||
"useTerm": "false",
|
||||
"noCheckPrivate": "false",
|
||||
"recTerms": "[]",
|
||||
"id": "0a464aedddbc6e4b9", # 无所谓
|
||||
"vendor": "fanyiweb_navigation",
|
||||
"in": "YoudaoDict_fanyiweb_navigation",
|
||||
"appVer": "10.1.3.0",
|
||||
"appZengqiang": "0",
|
||||
"abTest": "0",
|
||||
"model": "LENOVO",
|
||||
"screen": "1920*1080",
|
||||
"OsVersion": "10.0.19045",
|
||||
"network": "none",
|
||||
"mid": "windows10.0.19045",
|
||||
"appVersion": "10.1.3.0",
|
||||
"product": "deskdict",
|
||||
}
|
||||
elif v == 9:
|
||||
param = {
|
||||
"keyfrom": "deskdict.main",
|
||||
"client": "deskdict",
|
||||
"from": self.srclang,
|
||||
"to": self.tgtlang,
|
||||
"keyid": "deskdict",
|
||||
"mysticTime": mysticTime,
|
||||
"pointParam": "client,product,mysticTime",
|
||||
"sign": sign,
|
||||
"domain": "0",
|
||||
"useTerm": "false",
|
||||
"noCheckPrivate": "false",
|
||||
"id": "0a464aedddbc6e4b9",
|
||||
"vendor": "unknown",
|
||||
"in": "YoudaoDictSetup",
|
||||
"appVer": "9.3.0.0",
|
||||
"appZengqiang": "0",
|
||||
"abTest": "0",
|
||||
"model": "LENOVO",
|
||||
"screen": "1920*1080",
|
||||
"OsVersion": "10.0.19045",
|
||||
"appVersion": "9.3.0.0",
|
||||
"product": "deskdict",
|
||||
}
|
||||
elif v == 8:
|
||||
param = {
|
||||
"keyfrom": "deskdict.main",
|
||||
"client": "deskdict",
|
||||
"from": self.srclang,
|
||||
"to": self.tgtlang,
|
||||
"keyid": "deskdict",
|
||||
"mysticTime": mysticTime,
|
||||
"pointParam": "client,product,mysticTime",
|
||||
"sign": sign,
|
||||
"id": "0a464aedddbc6e4b9",
|
||||
"vendor": "unknown",
|
||||
"in": "YoudaoDictSetup",
|
||||
"appVer": "8.10.8.0",
|
||||
"appZengqiang": "0",
|
||||
"abTest": "0",
|
||||
"model": "LENOVO",
|
||||
"screen": "1920*1080",
|
||||
"OsVersion": "10.0.19045",
|
||||
"appVersion": "8.10.8.0",
|
||||
"product": "deskdict",
|
||||
}
|
||||
|
||||
param = {
|
||||
"keyfrom": "deskdict.main",
|
||||
"client": "deskdict",
|
||||
"from": self.srclang,
|
||||
"to": self.tgtlang,
|
||||
"keyid": "deskdict",
|
||||
"mysticTime": mysticTime,
|
||||
"pointParam": "client,product,mysticTime", # 只要不改pointParam,client,product,mysticTime,就不需要重新签名
|
||||
"sign": sign,
|
||||
"domain": "0",
|
||||
"useTerm": "false",
|
||||
"noCheckPrivate": "false",
|
||||
"recTerms": "[]",
|
||||
"id": "0a464aedddbc6e4b9", # 无所谓
|
||||
"vendor": "fanyiweb_navigation",
|
||||
"in": "YoudaoDict_fanyiweb_navigation",
|
||||
"appVer": "10.1.3.0",
|
||||
"appZengqiang": "0",
|
||||
"abTest": "0",
|
||||
"model": "LENOVO",
|
||||
"screen": "1920*1080",
|
||||
"OsVersion": "10.0.19045",
|
||||
"network": "none",
|
||||
"mid": "windows10.0.19045",
|
||||
"appVersion": "10.1.3.0",
|
||||
"product": "deskdict",
|
||||
}
|
||||
response = self.proxysession.post(
|
||||
"https://dict.youdao.com/dicttranslate",
|
||||
params=param,
|
||||
@ -133,13 +86,7 @@ class TS(basetrans):
|
||||
]
|
||||
)
|
||||
except:
|
||||
raise Exception(response.json())
|
||||
raise Exception(response.maybejson)
|
||||
|
||||
def translate(self, content):
|
||||
return self.translate10_9_8(content)
|
||||
if self.config["Version"] == 0: # 10
|
||||
return self.translate10_9_8(content)
|
||||
if self.config["Version"] == 1: # 9
|
||||
return self.translate10_9_8(content, 9)
|
||||
if self.config["Version"] == 2: # 8
|
||||
return self.translate10_9_8(content, 8)
|
||||
|
@ -1,5 +1,5 @@
|
||||
import requests
|
||||
from urllib.parse import urljoin
|
||||
from myutils.utils import urlpathjoin
|
||||
from tts.basettsclass import TTSbase
|
||||
from urllib.parse import quote
|
||||
|
||||
@ -7,7 +7,7 @@ from urllib.parse import quote
|
||||
class TTS(TTSbase):
|
||||
def getvoicelist(self):
|
||||
responseVits = requests.get(
|
||||
urljoin(self.config["URL"], self.config["voices"])
|
||||
urlpathjoin(self.config["URL"], self.config["voices"])
|
||||
).json()
|
||||
voicelist = []
|
||||
internal = []
|
||||
@ -26,6 +26,6 @@ class TTS(TTSbase):
|
||||
speak = self.config["speak"].format(
|
||||
model_lower=model.lower(), model=model, id=idx, text=encoded_content
|
||||
)
|
||||
response = requests.get(urljoin(self.config["URL"], speak)).content
|
||||
response = requests.get(urlpathjoin(self.config["URL"], speak)).content
|
||||
|
||||
return response
|
||||
|
@ -211,13 +211,20 @@
|
||||
"geminiocr": {
|
||||
"args": {
|
||||
"key": "",
|
||||
"url": "https://generativelanguage.googleapis.com/v1",
|
||||
"BASE_URL": "https://generativelanguage.googleapis.com/",
|
||||
"model": "gemini-1.5-flash",
|
||||
"use_custom_prompt": false,
|
||||
"modellistcache": [],
|
||||
"custom_prompt": ""
|
||||
},
|
||||
"argstype": {
|
||||
"BASE_URL": {
|
||||
"rank": 0
|
||||
},
|
||||
"key": {
|
||||
"rank": 2,
|
||||
"name": "API Key"
|
||||
},
|
||||
"custom_prompt": {
|
||||
"name": "自定义_promt",
|
||||
"type": "multiline",
|
||||
@ -228,6 +235,7 @@
|
||||
"name": "使用自定义promt"
|
||||
},
|
||||
"model": {
|
||||
"rank": 3,
|
||||
"type": "lineedit_or_combo",
|
||||
"list_function": "list_models",
|
||||
"list_cache": "modellistcache"
|
||||
|
@ -968,6 +968,7 @@
|
||||
"args": {
|
||||
"SECRET_KEY": "",
|
||||
"Temperature": 0.3,
|
||||
"BASE_URL": "https://generativelanguage.googleapis.com",
|
||||
"model": "gemini-1.5-flash",
|
||||
"modellistcache": [],
|
||||
"context": 0,
|
||||
@ -996,6 +997,9 @@
|
||||
"refswitch": "use_other_args",
|
||||
"name": "其他参数"
|
||||
},
|
||||
"BASE_URL": {
|
||||
"rank": 0
|
||||
},
|
||||
"usingstream": {
|
||||
"name": "流式输出",
|
||||
"type": "switch",
|
||||
|
Loading…
x
Reference in New Issue
Block a user