supermemo-toolkit 0.2.12__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- supermemo_toolkit/Icon.png +0 -0
- supermemo_toolkit/__init__.py +1 -0
- supermemo_toolkit/ansm_conv/__init__.py +0 -0
- supermemo_toolkit/ansm_conv/anki2sm.py +109 -0
- supermemo_toolkit/ansm_conv/ankinet.py +43 -0
- supermemo_toolkit/ansm_conv/sm2anki.py +138 -0
- supermemo_toolkit/autotts/__init__.py +0 -0
- supermemo_toolkit/autotts/autotts.py +326 -0
- supermemo_toolkit/autotts/replace.py +1024 -0
- supermemo_toolkit/autotts/switcher.py +335 -0
- supermemo_toolkit/autotts/threader.py +129 -0
- supermemo_toolkit/autotts/ui.py +156 -0
- supermemo_toolkit/database/__init__.py +0 -0
- supermemo_toolkit/database/control_click.py +575 -0
- supermemo_toolkit/database/element_no.py +446 -0
- supermemo_toolkit/database/force_reload.py +373 -0
- supermemo_toolkit/database/htmtext.py +193 -0
- supermemo_toolkit/database/origin_window.py +260 -0
- supermemo_toolkit/database/registry.py +380 -0
- supermemo_toolkit/database/trace.py +283 -0
- supermemo_toolkit/database/trigger_menu.py +186 -0
- supermemo_toolkit/database/window_focus.py +397 -0
- supermemo_toolkit/epub2sm/__init__.py +0 -0
- supermemo_toolkit/epub2sm/epub_convert.py +613 -0
- supermemo_toolkit/epub2sm/format_ascii.py +89 -0
- supermemo_toolkit/epub2sm/toc_check.py +68 -0
- supermemo_toolkit/epub2sm/toc_orgnize.py +200 -0
- supermemo_toolkit/latex2img/__init__.py +0 -0
- supermemo_toolkit/latex2img/bridge.py +46 -0
- supermemo_toolkit/latex2img/formula_to_png.py +174 -0
- supermemo_toolkit/latex2img/renderer.py +364 -0
- supermemo_toolkit/launcher.py +1799 -0
- supermemo_toolkit/pathpix/LICENSE.txt +21 -0
- supermemo_toolkit/pathpix/__init__.py +0 -0
- supermemo_toolkit/pathpix/epub_imgfit.py +254 -0
- supermemo_toolkit/pathpix/gui.py +271 -0
- supermemo_toolkit/pathpix/im_sort_out.py +1134 -0
- supermemo_toolkit/smtk.py +1212 -0
- supermemo_toolkit/smtk_shell.py +491 -0
- supermemo_toolkit/time_rewind/__init__.py +0 -0
- supermemo_toolkit/time_rewind/time_rewind.py +2794 -0
- supermemo_toolkit/title_xref/__init__.py +0 -0
- supermemo_toolkit/title_xref/complete_title.py +209 -0
- supermemo_toolkit/utilscripts/__init__.py +0 -0
- supermemo_toolkit/utilscripts/config.py +200 -0
- supermemo_toolkit/utilscripts/connector.py +336 -0
- supermemo_toolkit/utilscripts/launcher.vbs +838 -0
- supermemo_toolkit/utilscripts/query_menu.py +475 -0
- supermemo_toolkit/utilscripts/shortcut.py +136 -0
- supermemo_toolkit/utilscripts/ulils.py +108 -0
- supermemo_toolkit-0.2.12.dist-info/METADATA +259 -0
- supermemo_toolkit-0.2.12.dist-info/RECORD +55 -0
- supermemo_toolkit-0.2.12.dist-info/WHEEL +4 -0
- supermemo_toolkit-0.2.12.dist-info/entry_points.txt +5 -0
- supermemo_toolkit-0.2.12.dist-info/licenses/LICENSE +339 -0
|
Binary file
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.2.12"
|
|
File without changes
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import pystache
|
|
2
|
+
import pystache.defaults
|
|
3
|
+
from premailer import transform
|
|
4
|
+
|
|
5
|
+
from supermemo_toolkit.ansm_conv.ankinet import invoke
|
|
6
|
+
|
|
7
|
+
# note_id_list = invoke("findNotes", query="deck:24意境语义红宝石")
|
|
8
|
+
# notesInfo = invoke("notesInfo", notes=note_id_list)
|
|
9
|
+
|
|
10
|
+
# # modelName = notesInfo[29]["modelName"]
|
|
11
|
+
# findModelsByName = invoke("findModelsByName", modelNames=["Basic"])
|
|
12
|
+
|
|
13
|
+
# model.type\model.tmpls\model.css
|
|
14
|
+
# findModelsByName[0]['type'] 模型类型
|
|
15
|
+
# findModelsByName[0]['css'] CSS
|
|
16
|
+
# findModelsByName[0]['tmpls'][0]['name']
|
|
17
|
+
# findModelsByName[0]['tmpls'][0]['qfmt'] 问题模版
|
|
18
|
+
# findModelsByName[0]['tmpls'][0]['afmt'] 答案模版
|
|
19
|
+
# findModelsByName[0]['tmpls'][0]['did']
|
|
20
|
+
# findModelsByName[0]['tmpls'][0]['bqfmt']
|
|
21
|
+
# findModelsByName[0]['tmpls'][0]['bafmt']
|
|
22
|
+
# 第一个[0]对应的是请求的是一个列表,与列表下标对应的回应。
|
|
23
|
+
# 第二个[0]对应的就是模版下面的卡片了。默认是一个卡片。
|
|
24
|
+
# 然后就是mustache.render渲染卡片绑定笔记字段。
|
|
25
|
+
# 然后根据SuperMemo的模版情况,设置anki笔记的CSS,如何存放。
|
|
26
|
+
# https://github.com/anki2smArchive/anki2sm/blob/561035dd9f0077316cf7a4c3d7daa616fa7bfccf/anki2smV2.py#L368-L416
|
|
27
|
+
# <style>在QA中都有了。premailer.transform将样式属性直接嵌入到 HTML 元素中
|
|
28
|
+
# for index, noteInfo in enumerate(notesInfo):
|
|
29
|
+
# noteId = noteInfo["noteId"]
|
|
30
|
+
# fields = noteInfo["fields"]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
# anki2sm :选择卡组,选择输出路径。
|
|
34
|
+
# sm2anki:选择xml,选择卡组。
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def list():
|
|
38
|
+
desk = set()
|
|
39
|
+
deckNames: str[list] = invoke("deckNames")
|
|
40
|
+
for deckname in deckNames:
|
|
41
|
+
desk.add(deckname.split("::")[0])
|
|
42
|
+
for name in desk:
|
|
43
|
+
print(f"deckNames: {name}")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def a2s(deck: str):
|
|
47
|
+
note_id_list = invoke("findNotes", query=f"deck:{deck}")
|
|
48
|
+
notesInfo = invoke("notesInfo", notes=note_id_list)
|
|
49
|
+
if len(notesInfo) == 0:
|
|
50
|
+
print(f"{deck} notes is 0")
|
|
51
|
+
return
|
|
52
|
+
findModelsByName = invoke(
|
|
53
|
+
"findModelsByName", modelNames=[notesInfo[0]["modelName"]]
|
|
54
|
+
)
|
|
55
|
+
Model = findModelsByName[0]
|
|
56
|
+
|
|
57
|
+
card_tmpls = 0
|
|
58
|
+
type = Model["type"]
|
|
59
|
+
css = Model["css"]
|
|
60
|
+
name = Model["tmpls"][card_tmpls]["name"]
|
|
61
|
+
qfmt = Model["tmpls"][card_tmpls]["qfmt"]
|
|
62
|
+
afmt = Model["tmpls"][card_tmpls]["afmt"]
|
|
63
|
+
|
|
64
|
+
for noteInfo in notesInfo:
|
|
65
|
+
fields = noteInfo["fields"]
|
|
66
|
+
note_fields = {}
|
|
67
|
+
for name, value in fields.items():
|
|
68
|
+
note_fields.update({name: value["value"]})
|
|
69
|
+
# 将字段嵌入到模版中。
|
|
70
|
+
# 将样式嵌入到元素中。
|
|
71
|
+
# 渲染模版并得到静态结果无JS代码。
|
|
72
|
+
# 需要模拟anki的js环境。这个js该如何处理,我需要的是静态的无js的。
|
|
73
|
+
renderer = pystache.Renderer(
|
|
74
|
+
escape=lambda u: u, file_encoding=pystache.defaults.DELIMITERS
|
|
75
|
+
)
|
|
76
|
+
if type == 0:
|
|
77
|
+
questionTg = (
|
|
78
|
+
f"<style>{css}</style>"
|
|
79
|
+
+ "<section class='card' style=\" height:100%; width:100%; margin:0; \">"
|
|
80
|
+
+ renderer.render(qfmt, note_fields)
|
|
81
|
+
+ "</section>"
|
|
82
|
+
)
|
|
83
|
+
answerTag = (
|
|
84
|
+
f"<style>{css}</style>"
|
|
85
|
+
+ "<section class='card' style=\" height:100%; width:100%; margin:0; \">"
|
|
86
|
+
+ renderer.render(afmt, note_fields)
|
|
87
|
+
+ "</section>"
|
|
88
|
+
)
|
|
89
|
+
questionTg = transform(questionTg)
|
|
90
|
+
answerTag = transform(answerTag)
|
|
91
|
+
|
|
92
|
+
elif type == 1:
|
|
93
|
+
questionTg = (
|
|
94
|
+
f"<style>{css}</style>"
|
|
95
|
+
+ "<section class='card' style=\" height:100%; width:100%; margin:0; \">"
|
|
96
|
+
+ renderer.render(qfmt, note_fields)
|
|
97
|
+
+ "</section>"
|
|
98
|
+
)
|
|
99
|
+
answerTag = (
|
|
100
|
+
f"<style>{css}</style>"
|
|
101
|
+
+ "<section class='card' style=\" height:100%; width:100%; margin:0; \">"
|
|
102
|
+
+ renderer.render(afmt, note_fields)
|
|
103
|
+
+ "</section>"
|
|
104
|
+
)
|
|
105
|
+
questionTg = transform(questionTg)
|
|
106
|
+
answerTag = transform(answerTag)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
a2s("24意境语义红宝石")
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import urllib.request
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def request(action, **params):
|
|
6
|
+
return {"action": action, "params": params, "version": 6}
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def invoke(action, **params):
|
|
10
|
+
requestJson = json.dumps(request(action, **params)).encode("utf-8")
|
|
11
|
+
response = json.load(
|
|
12
|
+
urllib.request.urlopen(
|
|
13
|
+
urllib.request.Request("http://127.0.0.1:8765", requestJson)
|
|
14
|
+
)
|
|
15
|
+
)
|
|
16
|
+
if len(response) != 2:
|
|
17
|
+
raise Exception("response has an unexpected number of fields")
|
|
18
|
+
if "error" not in response:
|
|
19
|
+
raise Exception("response is missing required error field")
|
|
20
|
+
if "result" not in response:
|
|
21
|
+
raise Exception("response is missing required result field")
|
|
22
|
+
if response["error"] is not None:
|
|
23
|
+
raise Exception(response["error"])
|
|
24
|
+
return response["result"]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def str_en_zh_split(mstring: str):
|
|
28
|
+
for i, s in enumerate(mstring):
|
|
29
|
+
if not s.isascii():
|
|
30
|
+
return (mstring[:i], mstring[i:])
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def backward_erasure(onelist: list, savelen: int) -> list:
|
|
34
|
+
"""
|
|
35
|
+
给一个列表, 从后往前删除, 并保留前savelen个。
|
|
36
|
+
"""
|
|
37
|
+
mindex = len(onelist) - 1
|
|
38
|
+
for i in range(mindex, -1, -1):
|
|
39
|
+
llen = i + 1
|
|
40
|
+
if llen <= savelen:
|
|
41
|
+
break
|
|
42
|
+
del onelist[i]
|
|
43
|
+
return onelist
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import html
|
|
2
|
+
|
|
3
|
+
from supermemo_toolkit.ansm_conv.ankinet import invoke
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class qa_to_anki:
|
|
7
|
+
def __init__(self, qafile):
|
|
8
|
+
self.qafile = qafile
|
|
9
|
+
self.deckName = "SuperMemo Cards"
|
|
10
|
+
self.modelName = "问答题(SuperMemo)"
|
|
11
|
+
|
|
12
|
+
def setDeckName(self, deckName: str):
|
|
13
|
+
self.deckName = deckName
|
|
14
|
+
|
|
15
|
+
def __addNote(self, deckName: str, fields: dict):
|
|
16
|
+
try:
|
|
17
|
+
invoke(
|
|
18
|
+
"addNote",
|
|
19
|
+
note={
|
|
20
|
+
"deckName": deckName,
|
|
21
|
+
"modelName": self.modelName,
|
|
22
|
+
"fields": fields,
|
|
23
|
+
"options": {
|
|
24
|
+
"allowDuplicate": False,
|
|
25
|
+
"duplicateScope": "deck",
|
|
26
|
+
"duplicateScopeOptions": {
|
|
27
|
+
"deckName": deckName,
|
|
28
|
+
"checkChildren": False,
|
|
29
|
+
"checkAllModels": False,
|
|
30
|
+
},
|
|
31
|
+
},
|
|
32
|
+
},
|
|
33
|
+
)
|
|
34
|
+
except Exception as e:
|
|
35
|
+
print(f"{e}. ENum::{fields['ENum']}")
|
|
36
|
+
|
|
37
|
+
def __createModel(self):
|
|
38
|
+
modelNames = invoke("modelNames")
|
|
39
|
+
if self.modelName not in modelNames:
|
|
40
|
+
print(f"创建模型: {self.modelName}")
|
|
41
|
+
invoke(
|
|
42
|
+
"createModel",
|
|
43
|
+
modelName=self.modelName,
|
|
44
|
+
inOrderFields=["Question", "Answer", "ENum", "《》"],
|
|
45
|
+
css=".card {\n font-family: arial;\n font-size: 20px;\n text-align: center;\n color: black;\n background-color: white;\n}\n.cloze {\n color: rgb(255, 0, 0);\n background-color: rgb(255, 255, 0);\n}",
|
|
46
|
+
isCloze=False,
|
|
47
|
+
cardTemplates=[
|
|
48
|
+
{
|
|
49
|
+
"Name": "卡片1",
|
|
50
|
+
"Front": "{{Question}}<br /><div style='font-family: Arial; font-size: 12px; float: left; color: #dcdcdc'>{{《》}}》</div>",
|
|
51
|
+
"Back": '{{FrontSide}}<div id="back"><hr id="answer" /><span id="content">{{Answer}}</span></div><script>$("#content").text() === "" ? $("#back").hide() : null;</script>',
|
|
52
|
+
}
|
|
53
|
+
],
|
|
54
|
+
)
|
|
55
|
+
print(f"复用模型: {self.modelName}")
|
|
56
|
+
|
|
57
|
+
def __selectedDesk(self, deckName: str):
|
|
58
|
+
deckNames: str[list] = invoke("deckNames")
|
|
59
|
+
if deckName not in deckNames:
|
|
60
|
+
print(f"创建牌组: {deckName}")
|
|
61
|
+
invoke("createDeck", deck=deckName)
|
|
62
|
+
else:
|
|
63
|
+
print(f"命中牌组: {deckName}")
|
|
64
|
+
|
|
65
|
+
def __pre_proc(self, file: str) -> list:
|
|
66
|
+
"""输入TEQA文件, 输出list[qa dict]
|
|
67
|
+
|
|
68
|
+
Args:
|
|
69
|
+
file (str): TEQA文件路径
|
|
70
|
+
|
|
71
|
+
Returns:
|
|
72
|
+
list: list[dict_qa{}]
|
|
73
|
+
"""
|
|
74
|
+
with open(file, "r", encoding="GB18030") as f:
|
|
75
|
+
content = f.readlines()
|
|
76
|
+
qa_list = []
|
|
77
|
+
qa = []
|
|
78
|
+
for line in content:
|
|
79
|
+
# '<hr>\n' '\n'
|
|
80
|
+
if line != "<hr>\n" and line != "\n":
|
|
81
|
+
qa.append(line)
|
|
82
|
+
elif len(qa) != 0:
|
|
83
|
+
qa_list.append(qa)
|
|
84
|
+
qa = []
|
|
85
|
+
mqa_list = []
|
|
86
|
+
for qa in qa_list:
|
|
87
|
+
mqa = {}
|
|
88
|
+
for field in qa:
|
|
89
|
+
field: str = field.strip().split(": ", maxsplit=1)
|
|
90
|
+
name, value = field
|
|
91
|
+
mqa.update({name: html.unescape(value.strip())})
|
|
92
|
+
mqa_list.append(mqa)
|
|
93
|
+
return mqa_list
|
|
94
|
+
|
|
95
|
+
def __creat_anki_card(self, mqa_list: list):
|
|
96
|
+
# TEQA: Title, ENum, Question, Answer
|
|
97
|
+
# 行是检验知的最好方式,因为知行合一
|
|
98
|
+
for num, qa in enumerate(mqa_list):
|
|
99
|
+
print(
|
|
100
|
+
f"添加卡片: {num + 1}/{len(mqa_list)} ENum::{qa['E']}", end="\033[K\r"
|
|
101
|
+
)
|
|
102
|
+
if "Q" in qa and "A" in qa and "E" in qa:
|
|
103
|
+
self.__addNote(
|
|
104
|
+
self.deckName,
|
|
105
|
+
{
|
|
106
|
+
"Question": qa["Q"],
|
|
107
|
+
"Answer": qa["A"],
|
|
108
|
+
"ENum": qa["E"],
|
|
109
|
+
"《》": self.deckName,
|
|
110
|
+
},
|
|
111
|
+
)
|
|
112
|
+
elif "Q" in qa and "A" in qa:
|
|
113
|
+
self.__addNote(
|
|
114
|
+
self.deckName,
|
|
115
|
+
{
|
|
116
|
+
"Question": qa["Q"],
|
|
117
|
+
"Answer": qa["A"],
|
|
118
|
+
"《》": self.deckName,
|
|
119
|
+
},
|
|
120
|
+
)
|
|
121
|
+
elif "Q" in qa:
|
|
122
|
+
self.__addNote(
|
|
123
|
+
self.deckName,
|
|
124
|
+
{
|
|
125
|
+
"Question": qa["Q"],
|
|
126
|
+
"《》": self.deckName,
|
|
127
|
+
},
|
|
128
|
+
)
|
|
129
|
+
print("\nDone!")
|
|
130
|
+
|
|
131
|
+
def sent_cards(self):
|
|
132
|
+
try:
|
|
133
|
+
self.__createModel()
|
|
134
|
+
self.__selectedDesk(self.deckName)
|
|
135
|
+
qa_list = self.__pre_proc(self.qafile)
|
|
136
|
+
self.__creat_anki_card(qa_list)
|
|
137
|
+
except Exception as ex:
|
|
138
|
+
print(ex)
|
|
File without changes
|
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import threading
|
|
3
|
+
from tkinter import messagebox
|
|
4
|
+
|
|
5
|
+
import pyperclip
|
|
6
|
+
import win32gui
|
|
7
|
+
from pywinauto.findwindows import ElementNotFoundError
|
|
8
|
+
|
|
9
|
+
from supermemo_toolkit.autotts.replace import normalize_text
|
|
10
|
+
from supermemo_toolkit.autotts.switcher import AudioSwitcher
|
|
11
|
+
from supermemo_toolkit.autotts.ui import WinGUI
|
|
12
|
+
from supermemo_toolkit.database.htmtext import get_supermemo_html
|
|
13
|
+
from supermemo_toolkit.database.registry import TextRegistry
|
|
14
|
+
from supermemo_toolkit.database.trace import Trace
|
|
15
|
+
from supermemo_toolkit.utilscripts.connector import supermemo
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class AutoTTS:
|
|
19
|
+
def __init__(self, onlyat=False):
|
|
20
|
+
self.logger = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
if not onlyat:
|
|
23
|
+
self.trace: Trace = Trace()
|
|
24
|
+
if supermemo.ensure_snapshot() is None:
|
|
25
|
+
raise RuntimeError("AutoTTS 初始化失败,无法连接到 SuperMemo")
|
|
26
|
+
|
|
27
|
+
self.switcher = AudioSwitcher()
|
|
28
|
+
self.window: Win | None = None
|
|
29
|
+
self.trace_thread = None
|
|
30
|
+
self.stopped = True # 软件启动后手动启动监听
|
|
31
|
+
self.eid = None
|
|
32
|
+
self.title = None
|
|
33
|
+
self.legacy_version_his_window_text: str = ""
|
|
34
|
+
self.legacy_sm_closed: bool = False
|
|
35
|
+
|
|
36
|
+
def play_current_content(self, text_reg: TextRegistry = None):
|
|
37
|
+
"""在主线程里真正播放当前内容"""
|
|
38
|
+
if text_reg is None or text_reg.eId is None:
|
|
39
|
+
return
|
|
40
|
+
self.eid = text_reg.eId
|
|
41
|
+
self.title = text_reg.eTitle[:12].strip()
|
|
42
|
+
self.switcher.stop()
|
|
43
|
+
if self.stopped == True:
|
|
44
|
+
return
|
|
45
|
+
|
|
46
|
+
text = text_reg.get_component().Text
|
|
47
|
+
print(self.show_title())
|
|
48
|
+
if text != "":
|
|
49
|
+
text = normalize_text(text)
|
|
50
|
+
self.window.update_lable_text(self.show_title())
|
|
51
|
+
self.switcher.play(text)
|
|
52
|
+
# 保存到重播按钮
|
|
53
|
+
self.window.update_text(text)
|
|
54
|
+
|
|
55
|
+
def _on_trace_element_changed(self, text_reg):
|
|
56
|
+
"""Trace 线程里的回调,不能直接碰 Tk 控件"""
|
|
57
|
+
|
|
58
|
+
if self.window:
|
|
59
|
+
# 切回 Tk 主线程执行
|
|
60
|
+
self.window.after(0, lambda tr=text_reg: self.play_current_content(tr))
|
|
61
|
+
else:
|
|
62
|
+
self.play_current_content(text_reg)
|
|
63
|
+
|
|
64
|
+
def start_trace(self, mode="m"):
|
|
65
|
+
"""
|
|
66
|
+
mode: 'm' 使用内存读取,'o' 使用 watchdog observer
|
|
67
|
+
"""
|
|
68
|
+
if self.stopped == True:
|
|
69
|
+
return
|
|
70
|
+
|
|
71
|
+
def run():
|
|
72
|
+
if mode == "m":
|
|
73
|
+
self.trace.trace_with_mem(self._on_trace_element_changed)
|
|
74
|
+
elif mode == "o":
|
|
75
|
+
self.trace.trace_with_observer(self._on_trace_element_changed)
|
|
76
|
+
else:
|
|
77
|
+
raise ValueError("mode 只能是 'm' 或 'o'")
|
|
78
|
+
|
|
79
|
+
self.trace.set_running()
|
|
80
|
+
self.trace_thread = threading.Thread(target=run, daemon=True)
|
|
81
|
+
self.trace_thread.start()
|
|
82
|
+
self.stopped = False
|
|
83
|
+
|
|
84
|
+
def stop_trace(self):
|
|
85
|
+
if hasattr(self, "trace"):
|
|
86
|
+
self.trace.set_running(False)
|
|
87
|
+
self.switcher.stop()
|
|
88
|
+
self.stopped = True
|
|
89
|
+
|
|
90
|
+
def set_autotts_window(self, window: WinGUI):
|
|
91
|
+
self.window = window
|
|
92
|
+
|
|
93
|
+
def show_title(self) -> str:
|
|
94
|
+
return f"[TTS] [No. {self.eid}] [Title: {self.title[:12].strip()}]"
|
|
95
|
+
|
|
96
|
+
@staticmethod
|
|
97
|
+
def format_title(text: str) -> str:
|
|
98
|
+
title = text[:12].translate(str.maketrans("\n\r", " ")).strip()
|
|
99
|
+
return f"[TTS] [LEN: {len(text)}] [Title: {title}]"
|
|
100
|
+
|
|
101
|
+
def legacy(self):
|
|
102
|
+
def focusInArea() -> bool:
|
|
103
|
+
targetClassName = [
|
|
104
|
+
"TMsgDialog",
|
|
105
|
+
"TBitBtnTScrollBox",
|
|
106
|
+
"Internet Explorer_Server",
|
|
107
|
+
"TElWind",
|
|
108
|
+
"TBitBtn",
|
|
109
|
+
"TScrollBox",
|
|
110
|
+
"TTabControl",
|
|
111
|
+
"TToolBar",
|
|
112
|
+
"TButton",
|
|
113
|
+
"TPage",
|
|
114
|
+
]
|
|
115
|
+
focus_hwnd = win32gui.WindowFromPoint(win32gui.GetCursorPos())
|
|
116
|
+
focusClassName = win32gui.GetClassName(focus_hwnd)
|
|
117
|
+
return focusClassName in targetClassName
|
|
118
|
+
|
|
119
|
+
# 停止监听守卫,默认停止监听
|
|
120
|
+
if self.stopped:
|
|
121
|
+
self.window.after(500, self.legacy)
|
|
122
|
+
return
|
|
123
|
+
|
|
124
|
+
if supermemo.snapshot is None:
|
|
125
|
+
if supermemo.ensure_snapshot() is None:
|
|
126
|
+
if not self.legacy_sm_closed:
|
|
127
|
+
self.window.update_lable_text("[TTS] SuperMemo 已关闭,等待重启")
|
|
128
|
+
self.legacy_sm_closed = True
|
|
129
|
+
self.legacy_version_his_window_text = ""
|
|
130
|
+
self.window.after(2000, self.legacy)
|
|
131
|
+
return
|
|
132
|
+
self.legacy_sm_closed = False
|
|
133
|
+
self.legacy_version_his_window_text = ""
|
|
134
|
+
|
|
135
|
+
# 1. 光标位置必须在选定区域内
|
|
136
|
+
if not focusInArea():
|
|
137
|
+
self.window.after(500, self.legacy)
|
|
138
|
+
return
|
|
139
|
+
|
|
140
|
+
# 3. 历史最求窗口名和当前最前窗口名必须不一致
|
|
141
|
+
# 当光标在选定区域并且最前窗口为选定区域,说明目标窗口聚焦
|
|
142
|
+
foregroundWindowText = supermemo.window_text()
|
|
143
|
+
if not foregroundWindowText:
|
|
144
|
+
self.window.after(500, self.legacy)
|
|
145
|
+
return
|
|
146
|
+
|
|
147
|
+
if self.legacy_version_his_window_text != foregroundWindowText:
|
|
148
|
+
print(f"[Main] 窗口标题: {foregroundWindowText}")
|
|
149
|
+
app = supermemo.app
|
|
150
|
+
if app is None:
|
|
151
|
+
self.window.after(2000, self.legacy)
|
|
152
|
+
return
|
|
153
|
+
text = get_supermemo_html(app)
|
|
154
|
+
if text is not None and text != "":
|
|
155
|
+
print(self.format_title(text))
|
|
156
|
+
self.window.update_lable_text(self.format_title(text))
|
|
157
|
+
self.switcher.play(text)
|
|
158
|
+
# 保存到重播按钮
|
|
159
|
+
self.window.update_text(text)
|
|
160
|
+
self.legacy_version_his_window_text = foregroundWindowText
|
|
161
|
+
|
|
162
|
+
self.window.after(500, self.legacy)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class Controller:
|
|
166
|
+
# 导入UI类后,替换以下的 object 类型,将获得 IDE 属性提示功能
|
|
167
|
+
ui: WinGUI
|
|
168
|
+
|
|
169
|
+
def __init__(self, sm_ver: str = ""):
|
|
170
|
+
self.auto_tts: AutoTTS = None
|
|
171
|
+
self.sm_ver = sm_ver
|
|
172
|
+
|
|
173
|
+
def init(self, ui):
|
|
174
|
+
"""
|
|
175
|
+
得到UI实例,对组件进行初始化配置
|
|
176
|
+
"""
|
|
177
|
+
self.ui = ui
|
|
178
|
+
|
|
179
|
+
def onEClick(self, evt):
|
|
180
|
+
self.auto_tts.stopped = not self.auto_tts.stopped
|
|
181
|
+
if self.auto_tts.stopped:
|
|
182
|
+
if self.sm_ver not in ["sm15", "sm16"]:
|
|
183
|
+
self.auto_tts.stop_trace()
|
|
184
|
+
self.auto_tts.window.update_lable_text("AutoTTS 窗口监听 已停止")
|
|
185
|
+
else:
|
|
186
|
+
if self.sm_ver not in ["sm15", "sm16"]:
|
|
187
|
+
self.auto_tts.start_trace()
|
|
188
|
+
self.auto_tts.window.update_lable_text("AutoTTS 窗口监听 已恢复")
|
|
189
|
+
|
|
190
|
+
def onERightClick(self, evt):
|
|
191
|
+
self.auto_tts.switcher.stop()
|
|
192
|
+
self.auto_tts.window.update_lable_text("[TTS] play stopped")
|
|
193
|
+
|
|
194
|
+
def onAClick(self, evt):
|
|
195
|
+
# 目前为止所有获取内容都不是主动获得焦点的,而是被动获取
|
|
196
|
+
text: str = self.ui.last_text
|
|
197
|
+
if text is not None and text != "":
|
|
198
|
+
print(self.auto_tts.format_title(text))
|
|
199
|
+
self.auto_tts.window.update_lable_text(self.auto_tts.format_title(text))
|
|
200
|
+
self.auto_tts.switcher.play(text)
|
|
201
|
+
|
|
202
|
+
def onTClick(self, evt):
|
|
203
|
+
text = pyperclip.paste()
|
|
204
|
+
if text is not None and text != "":
|
|
205
|
+
print(self.auto_tts.format_title(text))
|
|
206
|
+
self.auto_tts.window.update_lable_text(self.auto_tts.format_title(text))
|
|
207
|
+
self.auto_tts.switcher.play(text)
|
|
208
|
+
self.auto_tts.window.update_text(text)
|
|
209
|
+
|
|
210
|
+
def set_autotts(self, autotts: AutoTTS):
|
|
211
|
+
self.auto_tts = autotts
|
|
212
|
+
|
|
213
|
+
def run_legacy_autotts(self):
|
|
214
|
+
self.auto_tts.legacy()
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
class Win(WinGUI):
|
|
218
|
+
ctl: Controller
|
|
219
|
+
|
|
220
|
+
def __init__(self, controller: Controller, onlyat=False, sm_ver: str = ""):
|
|
221
|
+
self.ctl = controller
|
|
222
|
+
self.sm_ver = sm_ver
|
|
223
|
+
super().__init__()
|
|
224
|
+
if onlyat:
|
|
225
|
+
self.__onlyat_event_bind()
|
|
226
|
+
else:
|
|
227
|
+
self.__full_event_bind()
|
|
228
|
+
self.__style_config()
|
|
229
|
+
self.ctl.init(self)
|
|
230
|
+
self.last_text = ""
|
|
231
|
+
|
|
232
|
+
def __full_event_bind(self):
|
|
233
|
+
self.tk_button_miik3xn9.bind("<Button-1>", self.ctl.onEClick)
|
|
234
|
+
self.tk_button_miik3xn9.bind("<Button-3>", self.ctl.onERightClick)
|
|
235
|
+
self.tk_button_miileno7.bind("<Button-1>", self.ctl.onAClick)
|
|
236
|
+
self.tk_button_mipjikfh.bind("<Button-1>", self.ctl.onTClick)
|
|
237
|
+
if self.sm_ver in ["sm15", "sm16"]:
|
|
238
|
+
self.menu.add_command(
|
|
239
|
+
label="重启监听",
|
|
240
|
+
command=lambda: self.after(500, self.ctl.run_legacy_autotts),
|
|
241
|
+
)
|
|
242
|
+
self.menu.add_command(
|
|
243
|
+
label="重置窗口位置", command=lambda: self.geometry(self.geometry_size)
|
|
244
|
+
)
|
|
245
|
+
self.menu.add_command(label="退出程序", command=self.quit)
|
|
246
|
+
|
|
247
|
+
def __onlyat_event_bind(self):
|
|
248
|
+
self.tk_button_miik3xn9.config(state="disabled")
|
|
249
|
+
self.tk_button_miileno7.bind("<Button-1>", self.ctl.onAClick)
|
|
250
|
+
self.tk_button_mipjikfh.bind("<Button-1>", self.ctl.onTClick)
|
|
251
|
+
self.menu.add_command(
|
|
252
|
+
label="重置窗口位置", command=lambda: self.geometry(self.geometry_size)
|
|
253
|
+
)
|
|
254
|
+
self.menu.add_command(label="退出程序", command=self.quit)
|
|
255
|
+
|
|
256
|
+
def quit(self):
|
|
257
|
+
"""退出程序"""
|
|
258
|
+
print("[Replay] 正在退出程序...")
|
|
259
|
+
# 设置守护线程的话,这边就直接终止不用等待? 然后我也可以join守护线程嘛?
|
|
260
|
+
# 不用,丢就丢了,通知到位就可以 join的话就丢不了了。
|
|
261
|
+
# exit(0) os._exit(0)
|
|
262
|
+
# 先暂停把,清理完成就退出了
|
|
263
|
+
try:
|
|
264
|
+
self.ctl.auto_tts.stop_trace()
|
|
265
|
+
self.ctl.auto_tts.switcher.stop()
|
|
266
|
+
finally:
|
|
267
|
+
self.destroy() # ← 销毁 Tk 窗口,mainloop() 立刻返回
|
|
268
|
+
|
|
269
|
+
def __style_config(self):
|
|
270
|
+
pass
|
|
271
|
+
|
|
272
|
+
def update_text(self, text):
|
|
273
|
+
"""更新要重播的文本内容"""
|
|
274
|
+
self.last_text = text
|
|
275
|
+
|
|
276
|
+
def update_lable_text(self, mtext):
|
|
277
|
+
"""更新要重播的文本内容"""
|
|
278
|
+
super().update_lable_text(mtext)
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def supermemo_ver():
|
|
282
|
+
"""兼容旧调用。返回 sm_ver 或 None(弹窗已弹)。"""
|
|
283
|
+
snap = supermemo.ensure_snapshot()
|
|
284
|
+
if snap is None:
|
|
285
|
+
err = supermemo.last_error
|
|
286
|
+
if isinstance(err, ElementNotFoundError):
|
|
287
|
+
messagebox.showerror("错误", "SuperMemo 可能未启动\n" + str(err))
|
|
288
|
+
else:
|
|
289
|
+
messagebox.showerror("错误", str(err) if err else "无法连接 SuperMemo")
|
|
290
|
+
return None
|
|
291
|
+
return snap.sm_ver
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def run_auto_tts(onlyat: bool = False):
|
|
295
|
+
if onlyat:
|
|
296
|
+
autotts = AutoTTS(onlyat=True)
|
|
297
|
+
controller = Controller()
|
|
298
|
+
autotts_window = Win(controller, onlyat=True)
|
|
299
|
+
autotts.set_autotts_window(autotts_window)
|
|
300
|
+
controller.set_autotts(autotts)
|
|
301
|
+
else:
|
|
302
|
+
sm_ver = supermemo_ver()
|
|
303
|
+
if sm_ver is None:
|
|
304
|
+
return # supermemo_ver 里已经弹过错误框,直接结束
|
|
305
|
+
|
|
306
|
+
try:
|
|
307
|
+
autotts = AutoTTS(onlyat=False) # 先连 SuperMemo
|
|
308
|
+
except Exception: # noqa: BLE001
|
|
309
|
+
return
|
|
310
|
+
|
|
311
|
+
controller = Controller(sm_ver)
|
|
312
|
+
autotts_window = Win(controller, onlyat=False, sm_ver=sm_ver) # 成功后再建窗口
|
|
313
|
+
autotts.set_autotts_window(autotts_window)
|
|
314
|
+
controller.set_autotts(autotts)
|
|
315
|
+
|
|
316
|
+
if sm_ver not in ["sm15", "sm16"]:
|
|
317
|
+
autotts.start_trace()
|
|
318
|
+
else:
|
|
319
|
+
autotts_window.after(500, controller.run_legacy_autotts)
|
|
320
|
+
|
|
321
|
+
autotts_window.mainloop()
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
if __name__ == "__main__":
|
|
325
|
+
# 点击下一个自动播放。或者自己复制自动播放。
|
|
326
|
+
run_auto_tts(onlyat=True)
|