')
if not content:
@@ -62,7 +61,9 @@ function safe_weblio_search_word(word){
}
"""
links = []
- style = self.parse_stylesheet(simplehtmlparser(html, "style", "
{}
'.format(style, self.klass, join)
+ return '
{}
'.format(
+ style, self.klass, join
+ )
def makelink(self, link):
if not self.cache.get(link):
- req = requests.get(
- link,
- proxies=self.proxy,
- )
+ req = self.proxysession.get(link)
html = req.text if req.status_code == 200 else ""
self.cache[link] = self.parse_stylesheet(html, self.klass)
diff --git a/py/LunaTranslator/cishu/youdao.py b/py/LunaTranslator/cishu/youdao.py
index 016b346d..99f38a95 100644
--- a/py/LunaTranslator/cishu/youdao.py
+++ b/py/LunaTranslator/cishu/youdao.py
@@ -1,8 +1,7 @@
-import requests
from urllib.parse import quote
-import re, os
+import re
from cishu.cishubase import cishubase
-from myutils.utils import get_element_by, simplehtmlparser, getlangsrc
+from myutils.utils import get_element_by, simplehtmlparser
from myutils.config import isascii
from language import Languages
@@ -10,14 +9,14 @@ from language import Languages
class youdao(cishubase):
def search(self, word: str):
- lang = getlangsrc()
+ lang = self.srclang
if lang == Languages.Auto:
if isascii(word):
lang = Languages.English
else:
lang = Languages.Japanese
url = "https://dict.youdao.com/result?word={}&lang={}".format(quote(word), lang)
- text = requests.get(url, proxies=self.proxy).text
+ text = self.proxysession.get(url).text
if not get_element_by("class", "word-head", text):
return
text = re.sub("
", "", text)
diff --git a/py/LunaTranslator/myutils/commonbase.py b/py/LunaTranslator/myutils/commonbase.py
index 01e35546..9e145a07 100644
--- a/py/LunaTranslator/myutils/commonbase.py
+++ b/py/LunaTranslator/myutils/commonbase.py
@@ -101,10 +101,6 @@ class commonbase:
def __init__(self, typename) -> None:
self.typename = typename
self.renewsesion()
- self.level2init()
def renewsesion(self):
self.proxysession = proxysession(self._globalconfig_key, self.typename)
-
- def level2init(self):
- pass
diff --git a/py/LunaTranslator/ocrengines/baseocrclass.py b/py/LunaTranslator/ocrengines/baseocrclass.py
index 8c8d7276..c70bb8b2 100644
--- a/py/LunaTranslator/ocrengines/baseocrclass.py
+++ b/py/LunaTranslator/ocrengines/baseocrclass.py
@@ -112,6 +112,10 @@ class baseocr(commonbase):
if l == Languages.Auto:
raise Exception(_TR("当前OCR引擎不支持设置语言为自动"))
+ def __init__(self, typename):
+ super().__init__(typename)
+ self.level2init()
+
def level2init(self):
self.needinit = True
try:
diff --git a/py/LunaTranslator/ocrengines/volcengine.py b/py/LunaTranslator/ocrengines/volcengine.py
index 37057845..7d49747e 100644
--- a/py/LunaTranslator/ocrengines/volcengine.py
+++ b/py/LunaTranslator/ocrengines/volcengine.py
@@ -1,12 +1,11 @@
import json
from collections import OrderedDict
-import requests
from urllib.parse import urlencode
from functools import reduce
import hmac, base64
import datetime
import pytz
-import hashlib, os
+import hashlib
import sys, threading
from urllib.parse import quote
@@ -382,8 +381,7 @@ class ApiInfo(object):
class Service(object):
def __init__(self, service_info, api_info):
self.service_info = service_info
- self.api_info = api_info
- self.session = requests.session()
+ self.api_info = api_info
def set_ak(self, ak):
self.service_info.credentials.set_ak(ak)
@@ -414,7 +412,7 @@ class Service(object):
return SignerV4.sign_url(r, self.service_info.credentials)
- def post(self, api, params, form, proxy):
+ def post(self, api, params, form, session):
if not (api in self.api_info):
raise Exception("no such api")
api_info = self.api_info[api]
@@ -426,11 +424,10 @@ class Service(object):
url = r.build()
- resp = self.session.post(
+ resp = session.post(
url,
headers=r.headers,
data=r.form,
- proxies=proxy,
)
if resp.status_code == 200:
return resp.text
@@ -511,10 +508,10 @@ class VisualService(Service):
)
return service_info
- def common_handler(self, api, form, proxy):
+ def common_handler(self, api, form, session):
params = dict()
try:
- res = self.post(api, params, form, proxy)
+ res = self.post(api, params, form, session)
res_json = json.loads(res)
return res_json
except Exception as e:
@@ -525,9 +522,9 @@ class VisualService(Service):
except:
raise Exception(str(e))
- def ocr_api(self, action, form, proxy):
+ def ocr_api(self, action, form, session):
try:
- res_json = self.common_handler(action, form, proxy)
+ res_json = self.common_handler(action, form, session)
return res_json
except Exception as e:
raise Exception(str(e))
@@ -561,7 +558,7 @@ class OCR(baseocr):
b64 = base64.b64encode(imagebinary)
form["image_base64"] = b64
- resp = visual_service.ocr_api("MultiLanguageOCR", form, self.proxy)
+ resp = visual_service.ocr_api("MultiLanguageOCR", form, self.proxysession)
try:
texts = [box["text"] for box in resp["data"]["ocr_infos"]]
boxs = self.flatten4point(
diff --git a/py/LunaTranslator/translator/basetranslator.py b/py/LunaTranslator/translator/basetranslator.py
index ba64d1e7..8f109c0a 100644
--- a/py/LunaTranslator/translator/basetranslator.py
+++ b/py/LunaTranslator/translator/basetranslator.py
@@ -90,7 +90,8 @@ class basetrans(commonbase):
using_gpt_dict = False
_compatible_flag_is_sakura_less_than_5_52_3 = True
- def level2init(self):
+ def __init__(self, typename):
+ super().__init__(typename)
if (self.transtype == "offline") and (not self.is_gpt_like):
globalconfig["fanyi"][self.typename]["useproxy"] = False
self.multiapikeycurrentidx = -1
diff --git a/py/LunaTranslator/translator/huoshanapi.py b/py/LunaTranslator/translator/huoshanapi.py
index 43e4055f..83100ebf 100644
--- a/py/LunaTranslator/translator/huoshanapi.py
+++ b/py/LunaTranslator/translator/huoshanapi.py
@@ -1,6 +1,5 @@
import json
from collections import OrderedDict
-import requests
from translator.basetranslator import basetrans
from urllib.parse import urlencode
from functools import reduce
@@ -311,9 +310,8 @@ class Service(object):
def __init__(self, service_info, api_info):
self.service_info = service_info
self.api_info = api_info
- self.session = requests.session()
- def json(self, api, params, body, proxy):
+ def json(self, api, params, body, session):
if not (api in self.api_info):
raise Exception("no such api")
api_info = self.api_info[api]
@@ -324,11 +322,10 @@ class Service(object):
SignerV4.sign(r, self.service_info.credentials)
url = r.build()
- resp = self.session.post(
+ resp = session.post(
url,
headers=r.headers,
data=r.body.encode("utf8").decode("latin1"),
- proxies=proxy,
)
if resp.status_code == 200:
return json.dumps(resp.json())
@@ -383,7 +380,7 @@ class Service(object):
return od
-def trans(TextList, k_access_key, k_secret_key, src, tgt, proxy):
+def trans(TextList, k_access_key, k_secret_key, src, tgt, session):
k_service_info = ServiceInfo(
"open.volcengineapi.com",
@@ -401,7 +398,7 @@ def trans(TextList, k_access_key, k_secret_key, src, tgt, proxy):
}
if src != Languages.Auto:
body.update({"SourceLanguage": src})
- res = service.json("translate", {}, json.dumps(body), proxy)
+ res = service.json("translate", {}, json.dumps(body), session)
return res
@@ -414,7 +411,7 @@ class TS(basetrans):
keyid = self.multiapikeycurrent["Access Key ID"]
acckey = self.multiapikeycurrent["Secret Access Key"]
- res = trans(query, keyid, acckey, self.srclang, self.tgtlang, self.proxy)
+ res = trans(query, keyid, acckey, self.srclang, self.tgtlang, self.proxysession)
try:
return "\n".join(
diff --git a/py/LunaTranslator/translator/lingva.py b/py/LunaTranslator/translator/lingva.py
index f1ac1b26..43983a23 100644
--- a/py/LunaTranslator/translator/lingva.py
+++ b/py/LunaTranslator/translator/lingva.py
@@ -1,5 +1,3 @@
-import requests
-import urllib
from urllib.parse import quote_plus
from translator.basetranslator import basetrans
from language import Languages
@@ -9,57 +7,11 @@ class TS(basetrans):
def langmap(self):
return {Languages.TradChinese: "zh_HANT"}
- # def inittranslator(self):
- # res=requests.get(self.config['host'],headers=
- # {
- # 'sec-ch-ua': '"Not?A_Brand";v="8", "Chromium";v="108", "Microsoft Edge";v="108"',
- # 'Referer': self.config['host'],
- # 'sec-ch-ua-mobile': '?0',
- # 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.46',
- # 'sec-ch-ua-platform': '"Windows"',
- # },proxies=self.proxy).text
- # _id=re.findall('buildId":"(.*?)"',res)[0]
- # self.url=self.config['host']+'_next/data/{}/%s/%s/%s.json'.format(_id)
def translate(self, content):
- # print(self.url%(self.srclang,self.tgtlang,urllib.parse.quote(content)))
-
+
x = self.proxysession.get(
"https://"
+ self.config["host"]
+ "/api/v1/%s/%s/%s" % (self.srclang, self.tgtlang, quote_plus(content)),
- headers={
- # 'authority': self.config['host'],
- # 'accept': '*/*',
- # 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
- # 'cache-control': 'no-cache',
- # 'pragma': 'no-cache',
- # 'referer': self.config['host'],
- # 'sec-ch-ua': '"Not?A_Brand";v="8", "Chromium";v="108", "Microsoft Edge";v="108"',
- # 'sec-ch-ua-mobile': '?0',
- # 'sec-ch-ua-platform': '"Windows"',
- # 'sec-fetch-dest': 'empty',
- # 'sec-fetch-mode': 'cors',
- # 'sec-fetch-site': 'same-origin',
- # 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.46',
- },
).json()
return x["translation"]
- x = requests.get(
- self.url % (self.srclang, self.tgtlang, urllib.parse.quote(content)),
- headers={
- "accept": "*/*",
- "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
- "cache-control": "no-cache",
- "pragma": "no-cache",
- "referer": self.config["host"],
- "sec-ch-ua": '"Not?A_Brand";v="8", "Chromium";v="108", "Microsoft Edge";v="108"',
- "sec-ch-ua-mobile": "?0",
- "sec-ch-ua-platform": '"Windows"',
- "sec-fetch-dest": "empty",
- "sec-fetch-mode": "cors",
- "sec-fetch-site": "same-origin",
- "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.46",
- },
- proxies=self.proxy,
- ).json()
- return x["pageProps"]["translation"]
diff --git a/py/LunaTranslator/tts/basettsclass.py b/py/LunaTranslator/tts/basettsclass.py
index 4755e5d9..05fb57a2 100644
--- a/py/LunaTranslator/tts/basettsclass.py
+++ b/py/LunaTranslator/tts/basettsclass.py
@@ -4,6 +4,8 @@ from myutils.wrapper import threader
from traceback import print_exc
from myutils.proxy import getproxy
from myutils.utils import LRUCache
+from myutils.commonbase import commonbase
+
class SpeechParam:
@@ -12,9 +14,7 @@ class SpeechParam:
self.pitch = pitch
-class TTSbase:
- typename = None
-
+class TTSbase(commonbase):
def init(self): ...
def getvoicelist(self):
# 分别返回内部标识名,显示
@@ -24,15 +24,6 @@ class TTSbase:
return None # fname ,若为None则是不需要文件直接朗读
####################
- # 一些可能需要的属性
- @property
- def proxy(self):
- return getproxy(("reader", self.typename))
-
- @property
- def config(self):
- return globalconfig["reader"][self.typename]["args"]
-
@property
def arg_not_sup(self):
return globalconfig["reader"][self.typename].get("arg_not_sup", [])
@@ -63,10 +54,12 @@ class TTSbase:
########################
+ _globalconfig_key = "reader"
+ _setting_dict = globalconfig["reader"]
def __init__(
self, typename, playaudiofunction, privateconfig=None, init=True, uid=None
) -> None:
- self.typename = typename
+ super().__init__(typename)
self.playaudiofunction = playaudiofunction
self.uid = uid
self.LRUCache = LRUCache(3)
diff --git a/py/LunaTranslator/tts/bcuttts.py b/py/LunaTranslator/tts/bcuttts.py
index 62d865c6..597b987b 100644
--- a/py/LunaTranslator/tts/bcuttts.py
+++ b/py/LunaTranslator/tts/bcuttts.py
@@ -1,4 +1,3 @@
-import requests
from tts.basettsclass import TTSbase, SpeechParam
@@ -17,11 +16,10 @@ class TTS(TTSbase):
"build": "2180020",
}
- response = requests.get(
+ response = self.proxysession.get(
"https://member.bilibili.com/x/mvp/material/list",
params=params,
headers=headers,
- proxies=self.proxy,
)
vis, inter = [], []
@@ -59,16 +57,14 @@ class TTS(TTSbase):
},
}
- response = requests.post(
+ response = self.proxysession.post(
"https://member.bilibili.com/x/material/rubick-interface/sync-task",
headers=headers,
json=json_data,
- proxies=self.proxy,
)
- response = requests.get(
+ response = self.proxysession.get(
response.json()["data"]["result"]["results"][0]["url"],
headers=headers,
- proxies=self.proxy,
)
return response.content
diff --git a/py/LunaTranslator/tts/edgetts.py b/py/LunaTranslator/tts/edgetts.py
index 03498760..ccf3ce52 100644
--- a/py/LunaTranslator/tts/edgetts.py
+++ b/py/LunaTranslator/tts/edgetts.py
@@ -1,4 +1,3 @@
-import requests
import pytz
import websocket
from datetime import datetime
@@ -6,7 +5,6 @@ import time
import re
import uuid, hashlib
import time
-import requests
import time
from tts.basettsclass import TTSbase, SpeechParam
@@ -107,12 +105,11 @@ class DRM:
class TTS(TTSbase):
def getvoicelist(self):
- alllist = requests.get(
+ alllist = self.proxysession.get(
"{}&Sec-MS-GEC={}&Sec-MS-GEC-Version={}".format(
VOICE_LIST, DRM.generate_sec_ms_gec(), SEC_MS_GEC_VERSION
),
headers=VOICE_HEADERS,
- proxies=self.proxy,
).json()
return [_["ShortName"] for _ in alllist], [_["FriendlyName"] for _ in alllist]
diff --git a/py/LunaTranslator/tts/gtts.py b/py/LunaTranslator/tts/gtts.py
index 92f2e3e4..c60f2614 100644
--- a/py/LunaTranslator/tts/gtts.py
+++ b/py/LunaTranslator/tts/gtts.py
@@ -1,10 +1,9 @@
# -*- coding: utf-8 -*-
import base64
-import json, time
-import logging, os
+import json
+import logging
import re
import urllib
-import requests
_langs = {
"af": "Afrikaans",
@@ -415,8 +414,8 @@ class gTTS:
# Language
self.lang_check = lang_check
+ lang = str(self.ref.srclang)
self.lang = lang
-
if self.lang_check:
# Fallback lang in case it is deprecated
self.lang = _fallback_deprecated_lang(lang)
@@ -439,7 +438,6 @@ class gTTS:
self.pre_processor_funcs = pre_processor_funcs
self.tokenizer_func = tokenizer_func
-
def _tokenize(self, text):
# Pre-clean
text = text.strip()
@@ -486,11 +484,10 @@ class gTTS:
log.debug("data-%i: %s", idx, data)
# Request
- r = requests.post(
+ r = self.ref.proxysession.post(
url=translate_url,
data=data,
headers=self.GOOGLE_TTS_HEADERS,
- proxies=self.ref.proxy,
)
# Prepare request
@@ -507,12 +504,6 @@ class gTTS:
return "f.req={}&".format(urllib.parse.quote(espaced_rpc))
def stream(self):
- try:
- requests.packages.urllib3.disable_warnings(
- requests.packages.urllib3.exceptions.InsecureRequestWarning
- )
- except:
- pass
prepared_requests = self._prepare_requests()
for idx, r in enumerate(prepared_requests):
@@ -596,13 +587,11 @@ class gTTSError(Exception):
from tts.basettsclass import TTSbase
-from myutils.utils import getlangsrc
-
class TTS(TTSbase):
def getvoicelist(self):
return [""], [""]
def speak(self, content, voice, _):
- tts = gTTS(self, content, lang=str(getlangsrc()))
+ tts = gTTS(self, content)
return tts.save()
diff --git a/py/LunaTranslator/tts/huoshantts.py b/py/LunaTranslator/tts/huoshantts.py
index aaaefbe7..677d3e4d 100644
--- a/py/LunaTranslator/tts/huoshantts.py
+++ b/py/LunaTranslator/tts/huoshantts.py
@@ -1,5 +1,3 @@
-from traceback import print_exc
-import requests
import base64
from tts.basettsclass import TTSbase
@@ -69,11 +67,10 @@ class TTS(TTSbase):
"text": content,
"speaker": voice,
} #
- response = requests.post(
+ response = self.proxysession.post(
"https://translate.volcengine.com/crx/tts/v1/",
headers=headers,
json=json_data,
- proxies=self.proxy,
)
b64 = base64.b64decode(response.json()["audio"]["data"])
diff --git a/py/LunaTranslator/tts/vitsSimpleAPI.py b/py/LunaTranslator/tts/vitsSimpleAPI.py
index d8913ce1..8acb9d1d 100644
--- a/py/LunaTranslator/tts/vitsSimpleAPI.py
+++ b/py/LunaTranslator/tts/vitsSimpleAPI.py
@@ -1,4 +1,3 @@
-import requests
from myutils.utils import urlpathjoin
from tts.basettsclass import TTSbase, SpeechParam
from urllib.parse import quote
@@ -6,7 +5,7 @@ from urllib.parse import quote
class TTS(TTSbase):
def getvoicelist(self):
- responseVits = requests.get(
+ responseVits = self.proxysession.get(
urlpathjoin(self.config["URL"], self.config["voices"])
).json()
voicelist = []
@@ -37,6 +36,6 @@ class TTS(TTSbase):
text=encoded_content,
length=length,
)
- response = requests.get(urlpathjoin(self.config["URL"], speak)).content
+ response = self.proxysession.get(urlpathjoin(self.config["URL"], speak)).content
return response
diff --git a/py/LunaTranslator/tts/voicevox.py b/py/LunaTranslator/tts/voicevox.py
index 98305333..282cb98b 100644
--- a/py/LunaTranslator/tts/voicevox.py
+++ b/py/LunaTranslator/tts/voicevox.py
@@ -1,6 +1,3 @@
-import time
-import requests, json
-from traceback import print_exc
from tts.basettsclass import TTSbase, SpeechParam
@@ -25,10 +22,9 @@ class TTS(TTSbase):
"sec-ch-ua-platform": '"Windows"',
}
- response = requests.get(
+ response = self.proxysession.get(
"http://127.0.0.1:{}/speakers".format(self.config["Port"]),
headers=headers,
- proxies={"http": None, "https": None},
).json()
vis = []
idxs = []
@@ -55,11 +51,10 @@ class TTS(TTSbase):
pitch = 0.015 * param.pitch
params = {"speaker": voice, "text": content}
- response = requests.post(
+ response = self.proxysession.post(
"http://localhost:{}/audio_query".format(self.config["Port"]),
params=params,
headers=headers,
- proxies={"http": None, "https": None},
)
headers = {
"Content-Type": "application/json",
@@ -67,7 +62,7 @@ class TTS(TTSbase):
resp = response.json()
resp.update({"speedScale": rate, "pitchScale": pitch})
params = {"speaker": voice}
- response = requests.post(
+ response = self.proxysession.post(
"http://localhost:{}/synthesis".format(self.config["Port"]),
params=params,
headers=headers,
diff --git a/py/LunaTranslator/tts/youdaotts.py b/py/LunaTranslator/tts/youdaotts.py
index 70aa2623..6a84106d 100644
--- a/py/LunaTranslator/tts/youdaotts.py
+++ b/py/LunaTranslator/tts/youdaotts.py
@@ -1,10 +1,9 @@
-import requests
from tts.basettsclass import TTSbase
class TTS(TTSbase):
def getvoicelist(self):
- return ["ja", "zh", "en"], ["Japanese","Chinese","English"]
+ return ["ja", "zh", "en"], ["Japanese", "Chinese", "English"]
def speak(self, content, voice, _):
@@ -28,10 +27,9 @@ class TTS(TTSbase):
"le": voice,
}
- response = requests.get(
+ response = self.proxysession.get(
"https://dict.youdao.com/dictvoice",
params=params,
headers=headers,
- proxies=self.proxy,
).content
return response