From 58019754fd1123baf671b9a07df40fab32707c59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=81=8D=E5=85=AE=E6=83=9A=E5=85=AE?= <1173718158@qq.com> Date: Sun, 12 Jan 2025 19:19:04 +0800 Subject: [PATCH] . --- cpp/version.cmake | 2 +- py/LunaTranslator/cishu/cishubase.py | 42 +++------------- py/LunaTranslator/cishu/goo.py | 5 +- py/LunaTranslator/cishu/japandict.py | 8 +-- py/LunaTranslator/cishu/jisho.py | 8 +-- py/LunaTranslator/cishu/mojidict.py | 8 ++- py/LunaTranslator/cishu/weblio.py | 16 +++--- py/LunaTranslator/cishu/youdao.py | 9 ++-- py/LunaTranslator/myutils/commonbase.py | 4 -- py/LunaTranslator/ocrengines/baseocrclass.py | 4 ++ py/LunaTranslator/ocrengines/volcengine.py | 21 ++++---- .../translator/basetranslator.py | 3 +- py/LunaTranslator/translator/huoshanapi.py | 13 ++--- py/LunaTranslator/translator/lingva.py | 50 +------------------ py/LunaTranslator/tts/basettsclass.py | 19 +++---- py/LunaTranslator/tts/bcuttts.py | 10 ++-- py/LunaTranslator/tts/edgetts.py | 5 +- py/LunaTranslator/tts/gtts.py | 21 ++------ py/LunaTranslator/tts/huoshantts.py | 5 +- py/LunaTranslator/tts/vitsSimpleAPI.py | 5 +- py/LunaTranslator/tts/voicevox.py | 11 ++-- py/LunaTranslator/tts/youdaotts.py | 6 +-- 22 files changed, 74 insertions(+), 201 deletions(-) diff --git a/cpp/version.cmake b/cpp/version.cmake index 7ea52709..70742d2a 100644 --- a/cpp/version.cmake +++ b/cpp/version.cmake @@ -1,7 +1,7 @@ set(VERSION_MAJOR 6) set(VERSION_MINOR 20) -set(VERSION_PATCH 0) +set(VERSION_PATCH 1) set(VERSION_REVISION 0) set(LUNA_VERSION "{${VERSION_MAJOR},${VERSION_MINOR},${VERSION_PATCH},${VERSION_REVISION}}") add_library(VERSION_DEF ${CMAKE_CURRENT_LIST_DIR}/version_def.cpp) diff --git a/py/LunaTranslator/cishu/cishubase.py b/py/LunaTranslator/cishu/cishubase.py index 1705b0e1..1dc0609f 100644 --- a/py/LunaTranslator/cishu/cishubase.py +++ b/py/LunaTranslator/cishu/cishubase.py @@ -1,9 +1,8 @@ from myutils.config import globalconfig from myutils.wrapper import threader from traceback import print_exc -from myutils.proxy import getproxy -from myutils.utils import SafeFormatter, getlangtgt, getlangsrc -from myutils.commonbase import ArgsEmptyExc, proxysession +from myutils.utils import SafeFormatter +from myutils.commonbase import commonbase import re, uuid from tinycss2 import parse_stylesheet, serialize from tinycss2.ast import ( @@ -13,7 +12,6 @@ from tinycss2.ast import ( ParseError, LiteralToken, ) -from language import Languages class DictTree: @@ -21,8 +19,7 @@ class DictTree: def childrens(self) -> list: ... -class cishubase: - typename = None +class cishubase(commonbase): def init(self): pass @@ -30,13 +27,8 @@ class cishubase: def search(self, word): return word - @property - def proxy(self): - return getproxy(("cishu", self.typename)) - def __init__(self, typename) -> None: - self.typename = typename - self.proxysession = proxysession("cishu", self.typename) + super().__init__(typename) self.callback = print self.needinit = True try: @@ -45,6 +37,9 @@ class cishubase: except: print_exc() + _globalconfig_key = "cishu" + _setting_dict = globalconfig["cishu"] + @threader def safesearch(self, sentence, callback): try: @@ -64,10 +59,6 @@ class cishubase: except: pass - @property - def config(self): - return globalconfig["cishu"][self.typename]["args"] - def _gptlike_createquery(self, query, usekey, tempk): user_prompt = ( self.config.get(tempk, "") if self.config.get(usekey, False) else "" @@ -82,25 +73,8 @@ class cishubase: template = self.config[tempk] else: template = "You are a professional dictionary assistant whose task is to help users search for information such as the meaning, pronunciation, etymology, synonyms, antonyms, and example sentences of {srclang} words. You should be able to handle queries in multiple languages and provide in-depth information or simple definitions according to user needs. You should reply in {tgtlang}." - tgt = getlangtgt() - src = getlangsrc() - langmap = Languages.create_langmap(Languages.createenglishlangmap()) - tgtlang = langmap.get(tgt, tgt) - srclang = langmap.get(src, src) - return fmt.format(template, srclang=srclang, tgtlang=tgtlang) - def checkempty(self, items): - emptys = [] - for item in items: - if (self.config[item]) == "": - emptys.append(item) - if len(emptys): - emptys_s = [] - argstype = self.config.get("argstype", {}) - for e in emptys: - name = argstype.get(e, {}).get("name", e) - emptys_s.append(name) - raise ArgsEmptyExc(emptys_s) + return fmt.format(template, srclang=self.srclang, tgtlang=self.tgtlang) def markdown_to_html(self, markdown_text: str): print(markdown_text) diff --git a/py/LunaTranslator/cishu/goo.py b/py/LunaTranslator/cishu/goo.py index 58bf59c5..981e9690 100644 --- a/py/LunaTranslator/cishu/goo.py +++ b/py/LunaTranslator/cishu/goo.py @@ -1,4 +1,3 @@ -import requests from urllib.parse import quote import re from myutils.utils import localcachehelper @@ -13,14 +12,14 @@ class goo(cishubase): def search(self, word): url = "https://dictionary.goo.ne.jp/srch/all/{}/m1u/".format(quote(word)) - x = requests.get(url, proxies=self.proxy).text + x = self.proxysession.get(url).text xx = re.findall("
([\\s\\S]*?)
", x) if not xx: return xx = "".join(xx).replace('href="/', 'href="https://dictionary.goo.ne.jp/') cssurl = "https://dictionary.goo.ne.jp/mix/css/app.css" if not self.cache[cssurl]: - origin = requests.get(cssurl, proxies=self.proxy).text + origin = self.proxysession.get(cssurl).text origin = ( origin.replace("width:1004px", "") .replace("width:1024px", "") diff --git a/py/LunaTranslator/cishu/japandict.py b/py/LunaTranslator/cishu/japandict.py index b6af74fc..233d2a37 100644 --- a/py/LunaTranslator/cishu/japandict.py +++ b/py/LunaTranslator/cishu/japandict.py @@ -1,4 +1,3 @@ -import requests from urllib.parse import quote from cishu.cishubase import cishubase from myutils.utils import get_element_by, localcachehelper @@ -13,10 +12,7 @@ class japandict(cishubase): def search(self, word): url = "https://www.japandict.com/?s={}&lang=eng&list=1".format(quote(word)) - html = requests.get( - url, - proxies=self.proxy, - ).text + html = self.proxysession.get(url).text check = get_element_by("class", "alert-heading", html) if check: @@ -27,7 +23,7 @@ class japandict(cishubase): res = re.sub('href="(.*?)"', 'href="https://www.japandict.com\\1"', res) csslink = "https://www.japandict.com/static/css/japandict.ac087f3ecbc8.css" if not self.style[csslink]: - css = requests.get(csslink, proxies=self.proxy).text + css = self.proxysession.get(csslink).text css = css.replace("padding-top:60px !important", "") css = self.parse_stylesheet(css, self.klass) self.style[csslink] = css diff --git a/py/LunaTranslator/cishu/jisho.py b/py/LunaTranslator/cishu/jisho.py index 8b6c11e5..ecab60c8 100644 --- a/py/LunaTranslator/cishu/jisho.py +++ b/py/LunaTranslator/cishu/jisho.py @@ -1,4 +1,3 @@ -import requests from urllib.parse import quote import re, threading from cishu.cishubase import cishubase @@ -99,10 +98,7 @@ function onclickbtn_xxxxxx_internal(_id) { link = "https://jisho.org/{}/{}".format(key, quote(word)) url = link - html = requests.get( - url, - proxies=self.proxy, - ).text + html = self.proxysession.get(url).text if get_element_by("id", "no-matches", html): return @@ -135,7 +131,7 @@ function onclickbtn_xxxxxx_internal(_id) { link = ss.group()[6:-1] if not self.style.get(link): self.style[link] = self.parse_stylesheet( - requests.get(link, proxies=self.proxy).text, self.klass + self.proxysession.get(link).text, self.klass ) saver["style"] = self.style[link] saver["primary"] = get_element_by("id", "result_area", res) + res.replace( diff --git a/py/LunaTranslator/cishu/mojidict.py b/py/LunaTranslator/cishu/mojidict.py index 94233e3e..3b0a5c34 100644 --- a/py/LunaTranslator/cishu/mojidict.py +++ b/py/LunaTranslator/cishu/mojidict.py @@ -1,4 +1,4 @@ -import requests, re, json, uuid +import re, json, uuid from cishu.cishubase import cishubase @@ -33,11 +33,10 @@ def mojiclicksearch(self, word): ensure_ascii=False, ).encode() - response = requests.post( + response = self.proxysession.post( "https://api.mojidict.com/parse/functions/word-clickSearchV2", headers=headers, data=data, - proxies=self.proxy, ) result = response.json()["result"]["result"] @@ -573,7 +572,7 @@ def mojiclicksearch(self, word): def mojizonghe(self, word): - response = requests.post( + response = self.proxysession.post( "https://api.mojidict.com/parse/functions/union-api", json={ "functions": [ @@ -610,7 +609,6 @@ def mojizonghe(self, word): "sec-fetch-site": "same-site", "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36", }, - proxies=self.proxy, ) result = "" diff --git a/py/LunaTranslator/cishu/weblio.py b/py/LunaTranslator/cishu/weblio.py index 18e68502..27ba27e8 100644 --- a/py/LunaTranslator/cishu/weblio.py +++ b/py/LunaTranslator/cishu/weblio.py @@ -1,4 +1,3 @@ -import requests from urllib.parse import quote, unquote from cishu.cishubase import cishubase from myutils.utils import simplehtmlparser_all, simplehtmlparser, localcachehelper @@ -13,7 +12,7 @@ class weblio(cishubase): def search(self, word): url = "https://www.weblio.jp/content/" + quote(word) - html = requests.get(url, proxies=self.proxy).text + html = self.proxysession.get(url).text head = simplehtmlparser_all(html, "div", '
') content = simplehtmlparser_all(html, "div", '
') 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