Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
214 lines (180 loc) · 8.44 KB
/
Copy pathmain.py
File metadata and controls
214 lines (180 loc) · 8.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
import sys
import os
import re
from PyQt6.QtWidgets import (QApplication, QWidget, QVBoxLayout, QHBoxLayout,
QLabel, QPushButton, QComboBox, QCheckBox,
QFileDialog, QMessageBox, QLineEdit)
from PyQt6.QtCore import Qt
from ebooklib import epub
class TextToApp(QWidget):
def __init__(self):
super().__init__()
self.input_file = ""
self.output_dir = ""
self.init_ui()
def init_ui(self):
self.setWindowTitle('TextTo - 格式转换工厂')
self.resize(500, 300)
self.setAcceptDrops(True) # 允许拖拽
layout = QVBoxLayout()
# 1. 格式选择
format_layout = QHBoxLayout()
format_layout.addWidget(QLabel("目标格式:"))
self.format_combo = QComboBox()
self.format_combo.addItem("EPUB")
# 将来可在这里 continue addItems ("PDF", "Word"...)
format_layout.addWidget(self.format_combo)
format_layout.addStretch()
layout.addLayout(format_layout)
# 2. 自动识别章节
self.toc_checkbox = QCheckBox("自动识别章节目录 (按'第x章'等规则匹配)")
self.toc_checkbox.setChecked(True) # 默认勾选
layout.addWidget(self.toc_checkbox)
# 3. 来源文件 (支持点击选择和拖拽)
input_layout = QHBoxLayout()
self.input_label = QLineEdit("请选择或拖入 .txt 文件")
self.input_label.setReadOnly(True)
input_btn = QPushButton("选择文件")
input_btn.clicked.connect(self.select_input_file)
input_layout.addWidget(self.input_label)
input_layout.addWidget(input_btn)
layout.addLayout(input_layout)
# 4. 输出目录
output_layout = QHBoxLayout()
self.output_label = QLineEdit("请选择输出目录")
self.output_label.setReadOnly(True)
output_btn = QPushButton("选择目录")
output_btn.clicked.connect(self.select_output_dir)
output_layout.addWidget(self.output_label)
output_layout.addWidget(output_btn)
layout.addLayout(output_layout)
# 提示文本
self.drop_hint = QLabel("提示:支持直接将 txt 文件拖拽到窗口中")
self.drop_hint.setStyleSheet("color: gray;")
self.drop_hint.setAlignment(Qt.AlignmentFlag.AlignCenter)
layout.addWidget(self.drop_hint)
# 5. 开始转换按钮
self.convert_btn = QPushButton("开始转换")
self.convert_btn.setMinimumHeight(40)
self.convert_btn.setStyleSheet("background-color: #007AFF; color: white; font-weight: bold; border-radius: 5px;")
self.convert_btn.clicked.connect(self.start_conversion)
layout.addWidget(self.convert_btn)
self.setLayout(layout)
# 拖拽事件处理
def dragEnterEvent(self, event):
if event.mimeData().hasUrls():
event.accept()
else:
event.ignore()
def dropEvent(self, event):
urls = event.mimeData().urls()
if urls:
file_path = urls[0].toLocalFile()
if file_path.lower().endswith('.txt'):
self.input_file = file_path
self.input_label.setText(self.input_file)
# 默认输出目录设为输入文件所在目录
self.output_dir = os.path.dirname(self.input_file)
self.output_label.setText(self.output_dir)
else:
QMessageBox.warning(self, "格式错误", "目前只支持拖拽 TXT 文件!")
def select_input_file(self):
file_path, _ = QFileDialog.getOpenFileName(self, "选择TXT文件", "", "Text Files (*.txt)")
if file_path:
self.input_file = file_path
self.input_label.setText(self.input_file)
if not self.output_dir:
self.output_dir = os.path.dirname(self.input_file)
self.output_label.setText(self.output_dir)
def select_output_dir(self):
dir_path = QFileDialog.getExistingDirectory(self, "选择输出目录")
if dir_path:
self.output_dir = dir_path
self.output_label.setText(self.output_dir)
def start_conversion(self):
if not self.input_file or not os.path.exists(self.input_file):
QMessageBox.warning(self, "错误", "请先选择有效的来源文件!")
return
if not self.output_dir or not os.path.exists(self.output_dir):
QMessageBox.warning(self, "错误", "请选择有效的输出目录!")
return
target_format = self.format_combo.currentText()
if target_format == "EPUB":
self.convert_to_epub()
def convert_to_epub(self):
try:
self.convert_btn.setText("转换中...")
self.convert_btn.setEnabled(False)
QApplication.processEvents() # 刷新界面
# --- 核心修改:智能探测文件编码,彻底解决乱码 ---
# 依次尝试常用的中文编码。gb18030 兼容 GBK 和 GB2312
encodings_to_try = ['utf-8-sig', 'utf-8', 'gb18030', 'gbk']
lines = []
for enc in encodings_to_try:
try:
with open(self.input_file, 'r', encoding=enc) as f:
lines = f.readlines()
break # 如果没报错,说明编码对了,跳出循环
except UnicodeDecodeError:
continue # 报错了就换下一种编码继续试
# 如果依然是空的(极端情况),使用 ignore 强制读取
if not lines:
with open(self.input_file, 'r', encoding='utf-8', errors='ignore') as f:
lines = f.readlines()
# ---------------------------------------------
book = epub.EpubBook()
base_name = os.path.splitext(os.path.basename(self.input_file))[0]
book.set_title(base_name)
book.set_language('zh-CN')
chapters = []
auto_toc = self.toc_checkbox.isChecked()
if auto_toc:
# 稍微优化了正则,兼容全角数字(0-9)和一些特殊的空格
pattern = re.compile(r'^\s*第[零一二三四五六七八九十百千万0-90-9]+[章回节卷集部].*')
current_title = "前言"
current_content = []
for line in lines:
if pattern.match(line):
if current_content: # 保存上一个章节
self.add_epub_chapter(book, chapters, current_title, current_content)
current_title = line.strip()
current_content = []
else:
current_content.append(line)
if current_content: # 保存最后一章
self.add_epub_chapter(book, chapters, current_title, current_content)
else:
self.add_epub_chapter(book, chapters, base_name, lines)
# 构建目录和骨架
book.toc = tuple(chapters)
book.add_item(epub.EpubNcx())
book.add_item(epub.EpubNav())
book.spine = ['nav'] + chapters
# 输出文件路径:原名-epub.epub
out_filename = f"{base_name}-epub.epub"
out_path = os.path.join(self.output_dir, out_filename)
epub.write_epub(out_path, book)
QMessageBox.information(self, "成功", f"转换完成!\n文件已保存至:\n{out_path}")
except Exception as e:
QMessageBox.critical(self, "转换失败", f"发生错误:{str(e)}")
finally:
self.convert_btn.setText("开始转换")
self.convert_btn.setEnabled(True)
def add_epub_chapter(self, book, chapters_list, title, lines):
c_id = f"chapter_{len(chapters_list)}"
c_file = f"{c_id}.xhtml"
c = epub.EpubHtml(title=title, file_name=c_file, lang='zh-CN')
# 组装 HTML 段落
html_content = [f"<h2>{title}</h2>"]
for line in lines:
text = line.strip()
if text:
html_content.append(f"<p>{text}</p>")
c.content = "\n".join(html_content)
book.add_item(c)
chapters_list.append(c)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = TextToApp()
ex.show()
sys.exit(app.exec())