This commit is contained in:
恍兮惚兮 2024-05-17 00:08:24 +08:00
parent bd04bd443b
commit 6f0132a166
16 changed files with 1251 additions and 145 deletions

View File

@ -1,4 +1,4 @@
from myutils.config import globalconfig, static_data from myutils.config import getlangsrc
import requests import requests
from urllib.parse import quote from urllib.parse import quote
import re import re
@ -11,7 +11,7 @@ class youdao(cishubase):
def srclang(self): def srclang(self):
try: try:
l = static_data["language_list_translator_inner"][globalconfig["srclang3"]] l = getlangsrc()
return l return l
except: except:

View File

@ -1,5 +1,5 @@
import os import os
from myutils.config import globalconfig, _TRL, static_data from myutils.config import globalconfig, _TRL, static_data,getlanguse
from gui.usefulwidget import getsimplecombobox, getcolorbutton from gui.usefulwidget import getsimplecombobox, getcolorbutton
@ -46,11 +46,7 @@ def setTablanglz(self):
"", "",
callback=lambda: os.startfile( callback=lambda: os.startfile(
os.path.abspath( os.path.abspath(
"./files/lang/{}.json".format( "./files/lang/{}.json".format(getlanguse())
static_data["language_list_translator_inner"][
globalconfig["languageuse"]
]
)
) )
), ),
icon="fa.gear", icon="fa.gear",

View File

@ -44,14 +44,14 @@ class AnkiWindow(QWidget):
def langdu(self): def langdu(self):
if gobject.baseobject.reader: if gobject.baseobject.reader:
self.audiopath.setText( gobject.baseobject.reader.ttscallback(
gobject.baseobject.reader.syncttstofile(self.currentword) self.currentword, self.audiopath.setText
) )
def langdu2(self): def langdu2(self):
if gobject.baseobject.reader: if gobject.baseobject.reader:
self.audiopath_sentence.setText( gobject.baseobject.reader.ttscallback(
gobject.baseobject.reader.syncttstofile(self.example.toPlainText()) self.example.toPlainText(), self.audiopath_sentence.setText
) )
@threader @threader
@ -205,27 +205,41 @@ class AnkiWindow(QWidget):
def loadfakefields(self): def loadfakefields(self):
if len(self.editpath.text()): if len(self.editpath.text()):
with open(self.editpath.text(), "rb") as image_file: try:
encoded_string = base64.b64encode(image_file.read()).decode("utf-8") with open(self.editpath.text(), "rb") as image_file:
encoded_string = '<img src="data:image/png;base64,{}">'.format( encoded_string = base64.b64encode(image_file.read()).decode("utf-8")
encoded_string encoded_string = '<img src="data:image/png;base64,{}">'.format(
) encoded_string
)
except:
encoded_string = ""
else: else:
encoded_string = "" encoded_string = ""
if len(self.audiopath.text()): if len(self.audiopath.text()):
with open(self.audiopath.text(), "rb") as image_file: try:
encoded_string2 = base64.b64encode(image_file.read()).decode("utf-8") with open(self.audiopath.text(), "rb") as image_file:
encoded_string2 = """<button onclick='document.getElementById("audio1111").play()'>play audio<audio controls id="audio1111" style="display: none"><source src="data:audio/mpeg;base64,{}"></audio></button>""".format( encoded_string2 = base64.b64encode(image_file.read()).decode(
encoded_string2 "utf-8"
) )
encoded_string2 = """<button onclick='document.getElementById("audio1111").play()'>play audio<audio controls id="audio1111" style="display: none"><source src="data:audio/mpeg;base64,{}"></audio></button>""".format(
encoded_string2
)
except:
encoded_string2 = ""
else: else:
encoded_string2 = "" encoded_string2 = ""
if len(self.audiopath_sentence.text()): if len(self.audiopath_sentence.text()):
with open(self.audiopath_sentence.text(), "rb") as image_file: try:
encoded_string3 = base64.b64encode(image_file.read()).decode("utf-8") with open(self.audiopath_sentence.text(), "rb") as image_file:
encoded_string3 = """<button onclick='document.getElementById("audio2222").play()'>play audio_sentence<audio controls id="audio2222" style="display: none"><source src="data:audio/mpeg;base64,{}"></audio></button>""".format( encoded_string3 = base64.b64encode(image_file.read()).decode(
encoded_string3 "utf-8"
) )
encoded_string3 = """<button onclick='document.getElementById("audio2222").play()'>play audio_sentence<audio controls id="audio2222" style="display: none"><source src="data:audio/mpeg;base64,{}"></audio></button>""".format(
encoded_string3
)
except:
encoded_string3 = ""
else: else:
encoded_string3 = "" encoded_string3 = ""
fields = { fields = {

View File

@ -1,5 +1,5 @@
from myutils.proxy import getproxy from myutils.proxy import getproxy
from myutils.config import globalconfig, _TR, static_data from myutils.config import getlangtgt, _TR, static_data, getlangsrc
from myutils.wrapper import stripwrapper from myutils.wrapper import stripwrapper
import requests import requests
@ -34,7 +34,7 @@ class commonbase:
@property @property
def srclang(self): def srclang(self):
try: try:
l = static_data["language_list_translator_inner"][globalconfig["srclang3"]] l = getlangsrc()
return self.langmap_[l] return self.langmap_[l]
except: except:
return "" return ""
@ -42,7 +42,7 @@ class commonbase:
@property @property
def tgtlang(self): def tgtlang(self):
try: try:
l = static_data["language_list_translator_inner"][globalconfig["tgtlang3"]] l = getlangtgt()
return self.langmap_[l] return self.langmap_[l]
except: except:
return "" return ""

View File

@ -187,14 +187,22 @@ if len(globalconfig["toolbutton"]["rank"]) != len(
) )
def getlanguse():
global language, languageshow
return static_data["language_list_translator_inner"][language]
def getlangsrc():
return static_data["language_list_translator_inner"][globalconfig["srclang3"]]
def getlangtgt():
return static_data["language_list_translator_inner"][globalconfig["tgtlang3"]]
def setlanguage(): def setlanguage():
global language, languageshow global language, languageshow
language = globalconfig["languageuse"] language = globalconfig["languageuse"]
try: try:
with open( with open(
"./files/lang/{}.json".format( "./files/lang/{}.json".format(getlanguse()),
static_data["language_list_translator_inner"][language]
),
"r", "r",
encoding="utf8", encoding="utf8",
) as ff: ) as ff:
@ -255,8 +263,6 @@ def saveallconfig():
"./userconfig/savehook_new_1.39.4.json", [savehook_new_list, savehook_new_data] "./userconfig/savehook_new_1.39.4.json", [savehook_new_list, savehook_new_data]
) )
safesave( safesave(
"./files/lang/{}.json".format( "./files/lang/{}.json".format(getlanguse()),
static_data["language_list_translator_inner"][language]
),
languageshow, languageshow,
) )

View File

@ -7,7 +7,7 @@ from myutils.config import (
postprocessconfig, postprocessconfig,
globalconfig, globalconfig,
savehook_new_data, savehook_new_data,
static_data, getlangsrc,
) )
@ -179,7 +179,7 @@ def _4_f(line):
def _6_fEX(line): def _6_fEX(line):
srclang = static_data["language_list_translator_inner"][globalconfig["srclang3"]] srclang = getlangsrc()
if srclang in ["zh", "ja"]: if srclang in ["zh", "ja"]:
white = "" white = ""
else: else:

View File

@ -15,6 +15,7 @@ from traceback import print_exc
from myutils.config import ( from myutils.config import (
globalconfig, globalconfig,
static_data, static_data,
getlanguse,
savehook_new_list, savehook_new_list,
savehook_new_data, savehook_new_data,
getdefaultsavehook, getdefaultsavehook,
@ -537,10 +538,6 @@ def parsemayberegexreplace(dict, res):
return res return res
def getlanguse():
return static_data["language_list_translator_inner"][globalconfig["languageuse"]]
def checkpostlangmatch(name): def checkpostlangmatch(name):
for item in static_data["transoptimi"]: for item in static_data["transoptimi"]:
if name == item["name"]: if name == item["name"]:

View File

@ -1,5 +1,5 @@
import os import os
from myutils.config import globalconfig, _TR, static_data from myutils.config import globalconfig, _TR, getlangsrc
from ocrengines.baseocrclass import baseocr from ocrengines.baseocrclass import baseocr
from ctypes import ( from ctypes import (
CDLL, CDLL,
@ -131,9 +131,7 @@ class OCR(baseocr):
return return
self._ocr.trydestroy() self._ocr.trydestroy()
path = "./files/ocr/{}".format( path = "./files/ocr/{}".format(getlangsrc())
static_data["language_list_translator_inner"][globalconfig["srclang3"]]
)
if not ( if not (
os.path.exists(path + "/det.onnx") os.path.exists(path + "/det.onnx")
and os.path.exists(path + "/rec.onnx") and os.path.exists(path + "/rec.onnx")

View File

@ -1,7 +1,7 @@
from traceback import print_exc from traceback import print_exc
from queue import Queue from queue import Queue
from myutils.config import globalconfig, translatorsetting, static_data from myutils.config import globalconfig, translatorsetting, getlangtgt
from threading import Thread from threading import Thread
import time, types import time, types
import zhconv, gobject import zhconv, gobject
@ -172,7 +172,7 @@ class basetrans(commonbase):
@property @property
def needzhconv(self): def needzhconv(self):
# The API does not support direct translation to Traditional Chinese, only Simplified Chinese can be translated first and then converted to Traditional Chinese # The API does not support direct translation to Traditional Chinese, only Simplified Chinese can be translated first and then converted to Traditional Chinese
l = static_data["language_list_translator_inner"][globalconfig["tgtlang3"]] l = getlangtgt()
return l == "cht" and "cht" not in self.langmap() return l == "cht" and "cht" not in self.langmap()
@property @property

View File

@ -1,6 +1,7 @@
from myutils.config import globalconfig from myutils.config import globalconfig
import threading, os import threading, os, functools
from myutils.wrapper import threader
from traceback import print_exc
class TTSbase: class TTSbase:
def init(self): def init(self):
@ -19,15 +20,16 @@ class TTSbase:
# 一些可能需要的属性 # 一些可能需要的属性
@property @property
def config(self): def config(self):
return self.privateconfig['args'] return self.privateconfig["args"]
@property @property
def privateconfig(self): def privateconfig(self):
return globalconfig["reader"][self.typename] return globalconfig["reader"][self.typename]
@property @property
def publicconfig(self): def publicconfig(self):
return globalconfig["ttscommon"] return globalconfig["ttscommon"]
######################## ########################
def __init__(self, typename, showlistsignal, mp3playsignal) -> None: def __init__(self, typename, showlistsignal, mp3playsignal) -> None:
@ -58,15 +60,14 @@ class TTSbase:
threading.Thread(target=_).start() threading.Thread(target=_).start()
def read(self, content, force=False): def read(self, content, force=False):
def _(content, force): def _(force, fname):
fname = self.syncttstofile(content)
volume = self.publicconfig["volume"] volume = self.publicconfig["volume"]
if fname: self.mp3playsignal.emit(fname, volume, force)
self.mp3playsignal.emit(fname, volume, force)
threading.Thread(target=_, args=(content, force)).start() self.ttscallback(content, functools.partial(_, force))
def syncttstofile(self, content): @threader
def ttscallback(self, content, callback):
if self.loadok == False: if self.loadok == False:
return return
if len(content) == 0: if len(content) == 0:
@ -77,5 +78,10 @@ class TTSbase:
rate = self.publicconfig["rate"] rate = self.publicconfig["rate"]
voice = self.privateconfig["voice"] voice = self.privateconfig["voice"]
voice_index = self.voicelist.index(voice) voice_index = self.voicelist.index(voice)
fname = self.speak(content, rate, voice, voice_index) try:
return os.path.abspath(fname) fname = self.speak(content, rate, voice, voice_index)
if fname:
callback(os.path.abspath(fname))
except:
print_exc()
return

File diff suppressed because it is too large Load Diff

View File

@ -24,36 +24,31 @@ class TTS(TTSbase):
def speak(self, content, rate, voice, voiceidx): def speak(self, content, rate, voice, voiceidx):
try: headers = {
headers = { "authority": "translate.volcengine.com",
"authority": "translate.volcengine.com", "accept": "application/json, text/plain, */*",
"accept": "application/json, text/plain, */*", "accept-language": "zh-CN,zh;q=0.9",
"accept-language": "zh-CN,zh;q=0.9", "origin": "chrome-extension://klgfhbdadaspgppeadghjjemk",
"origin": "chrome-extension://klgfhbdadaspgppeadghjjemk", "sec-fetch-dest": "empty",
"sec-fetch-dest": "empty", "sec-fetch-mode": "cors",
"sec-fetch-mode": "cors", "sec-fetch-site": "none",
"sec-fetch-site": "none", "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36", }
}
json_data = { json_data = {
"text": content, "text": content,
"speaker": voice, "speaker": voice,
} # } #
response = requests.post( response = requests.post(
"https://translate.volcengine.com/crx/tts/v1/", "https://translate.volcengine.com/crx/tts/v1/",
headers=headers, headers=headers,
json=json_data, json=json_data,
proxies={"http": None, "https": None}, proxies={"http": None, "https": None},
) )
fname = str(time.time()) fname = str(time.time())
b64 = base64.b64decode(response.json()["audio"]["data"]) b64 = base64.b64decode(response.json()["audio"]["data"])
os.makedirs("./cache/tts/", exist_ok=True) os.makedirs("./cache/tts/", exist_ok=True)
with open("./cache/tts/" + fname + ".mp3", "wb") as ff: with open("./cache/tts/" + fname + ".mp3", "wb") as ff:
ff.write(b64) ff.write(b64)
return "./cache/tts/" + fname + ".mp3" return "./cache/tts/" + fname + ".mp3"
except:
print_exc()
return None

View File

@ -126,16 +126,16 @@ class TTS(TTSbase):
def speak(self, content, rate, voice, voice_idx): def speak(self, content, rate, voice, voice_idx):
self.checkpath() self.checkpath()
# def _(): # def _():
if True:
try: try:
content.encode("shift-jis") content.encode("shift-jis")
except: except:
return return
code1 = content.encode("shift-jis") code1 = content.encode("shift-jis")
# print(code1) # print(code1)
windows.WriteFile(self.hPipe, code1) windows.WriteFile(self.hPipe, code1)
fname = windows.ReadFile(self.hPipe, 1024).decode("utf8") fname = windows.ReadFile(self.hPipe, 1024).decode("utf8")
if os.path.exists(fname): if os.path.exists(fname):
return fname return fname

View File

@ -115,17 +115,16 @@ class TTS(TTSbase):
def speak(self, content, rate, voice, voice_idx): def speak(self, content, rate, voice, voice_idx):
self.checkpath() self.checkpath()
# def _():
if True:
try: try:
content.encode("shift-jis") content.encode("shift-jis")
except: except:
return return
code1 = content.encode("shift-jis") code1 = content.encode("shift-jis")
# print(code1) # print(code1)
windows.WriteFile(self.hPipe, code1) windows.WriteFile(self.hPipe, code1)
fname = windows.ReadFile(self.hPipe, 1024).decode("utf8") fname = windows.ReadFile(self.hPipe, 1024).decode("utf8")
if os.path.exists(fname): if os.path.exists(fname):
return fname return fname

View File

@ -74,36 +74,33 @@ class TTS(TTSbase):
def speak(self, content, rate, voice, voiceidx): def speak(self, content, rate, voice, voiceidx):
# def _(): headers = {
if True: "Content-Type": "application/x-www-form-urlencoded",
}
headers = { params = {"speaker": voiceidx, "text": content}
"Content-Type": "application/x-www-form-urlencoded",
}
params = {"speaker": voiceidx, "text": content} response = requests.post(
f"http://localhost:{self.config['Port']}/audio_query",
response = requests.post( params=params,
f"http://localhost:{self.config['Port']}/audio_query", headers=headers,
params=params, proxies={"http": None, "https": None},
headers=headers, )
proxies={"http": None, "https": None}, print(response.json())
) fname = str(time.time())
print(response.json()) headers = {
fname = str(time.time()) "Content-Type": "application/json",
headers = { }
"Content-Type": "application/json", params = {
} "speaker": voiceidx,
params = { }
"speaker": voiceidx, response = requests.post(
} f"http://localhost:{self.config['Port']}/synthesis",
response = requests.post( params=params,
f"http://localhost:{self.config['Port']}/synthesis", headers=headers,
params=params, data=json.dumps(response.json()),
headers=headers, )
data=json.dumps(response.json()), os.makedirs("./cache/tts/", exist_ok=True)
) with open("./cache/tts/" + fname + ".wav", "wb") as ff:
os.makedirs("./cache/tts/", exist_ok=True) ff.write(response.content)
with open("./cache/tts/" + fname + ".wav", "wb") as ff: return "./cache/tts/" + fname + ".wav"
ff.write(response.content)
return "./cache/tts/" + fname + ".wav"

View File

@ -725,6 +725,11 @@
"name": "GPT-SOVITS preset" "name": "GPT-SOVITS preset"
} }
} }
},
"gtts": {
"use": false,
"name": "谷歌",
"voice": ""
} }
}, },
"hirasetting": { "hirasetting": {