-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRstTranslator.cpp
252 lines (214 loc) · 7.93 KB
/
RstTranslator.cpp
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
#include "RstTranslator.h"
#include <QCoreApplication>
#include <QDebug>
#include <QStringList>
#include <QTime>
RstTranslator::RstTranslator(int maxLen, int minLen)
: m_openaiManager(OpenaiManager::getInstance()), m_translatePrompt(RstPrompt::getInstance()),
m_maxLen(maxLen), m_minLen(minLen)
{
qDebug() << "初始化RST文件翻译";
m_translatePrompt->load(m_translatePrompt->getPromptPath());
m_rstParser.setMaxLength(m_maxLen);
m_rstParser.setMinLength(m_minLen);
}
RstTranslator::~RstTranslator() {}
bool RstTranslator::translate(const QString &inputFilePath, const QString &outputFilePath,
const QString &url, const QString &apiKey, const QString &model,
bool keepHistory)
{
QTime startTime = QTime::currentTime();
outlog("=== 开始翻译任务 ===");
outlog("RST文件: " + inputFilePath);
outlog("翻译模型: " + model);
outlog("");
// 解析RST文件
if (!m_rstParser.parse(inputFilePath))
{
outlog("[错误] 解析RST文件失败");
return false;
}
// 获取文本列表
QVector<RstInfo> rstInfoList = m_rstParser.getRstInfoList();
outlog(QString("共找到 %1 个段落").arg(rstInfoList.size()));
outlog("-------------------");
// 获取翻译提示信息
PromptInfo promptInfo = m_translatePrompt->getPrompt();
// 用于计算平均处理时间
QVector<int> processingTimes;
// 错误计数
int errCount = 0;
// 遍历文本列表进行翻译
for (int i = 0; i < rstInfoList.size(); ++i)
{
QTime itemStartTime = QTime::currentTime();
// 如果是空行,直接保留不翻译
if (rstInfoList[i].content.trimmed().isEmpty())
{
rstInfoList[i].translateContent = rstInfoList[i].content;
continue;
}
// 处理用户提示列表
QVector<QString> processedUserPrompts;
QVector<QString> processedAssistantPrompts;
// 先加入历史记录
for (const TranslateHistory &history : m_history)
{
processedUserPrompts.append(history.original);
processedAssistantPrompts.append(history.translated);
}
// 然后增加参考示例
for (const QString &userPrompt : promptInfo.userPromptList)
{
QString processedPrompt = buildPrompt(userPrompt, promptInfo);
processedUserPrompts.append(processedPrompt);
}
for (const QString &assistantPrompt : promptInfo.assistantPromptList)
{
processedAssistantPrompts.append(assistantPrompt);
}
outlog(QString("\n[进度 %1/%2]").arg(i + 1).arg(rstInfoList.size()));
outlog("原文: " + rstInfoList[i].content);
// 构建当前段落的翻译提示
QString currentPrompt = buildPrompt(rstInfoList[i].content, promptInfo);
// 创建新的用户提示列表,包含所有处理过的示例和当前段落
QVector<QString> finalUserPrompts = processedUserPrompts;
finalUserPrompts.append(currentPrompt);
// 调用OpenAI API进行翻译
QString translation = m_openaiManager->sendMessage(
url, apiKey, model, promptInfo.prompt, finalUserPrompts, processedAssistantPrompts);
if (translation.isEmpty())
{
outlog("[错误] 翻译失败,跳过当前段落");
outlog("-------------------");
errCount++;
continue;
}
outlog("译文: " + translation);
// 保存翻译结果
if (!translation.isEmpty())
{
rstInfoList[i].translateContent = translation + "\n\n";
if (keepHistory)
{
TranslateHistory history;
history.original = currentPrompt;
history.translated = translation;
m_history.append(history);
// 保持历史记录不超过限制
const int maxHistory = 1;
while (m_history.size() > maxHistory)
{
m_history.removeFirst();
}
}
}
else
{
outlog("[警告] 未找到有效的翻译内容,使用原文");
rstInfoList[i].translateContent = rstInfoList[i].content;
}
// 计算本段落的处理时间
int processTime = itemStartTime.msecsTo(QTime::currentTime());
processingTimes.append(processTime);
// 计算平均处理时间和预计剩余时间
if (processingTimes.size() > 0)
{
// 计算平均处理时间(毫秒)
qint64 avgTime = 0;
for (int time : processingTimes)
{
avgTime += time;
}
avgTime /= processingTimes.size();
// 计算预计剩余时间
int remainingItems = rstInfoList.size() - (i + 1);
qint64 estimatedRemainingTime = avgTime * remainingItems;
// 转换为更友好的时间格式
QString timeStr;
if (estimatedRemainingTime < 1000)
{
timeStr = QString("%1毫秒").arg(estimatedRemainingTime);
}
else if (estimatedRemainingTime < 60000)
{
timeStr = QString("%1秒").arg(estimatedRemainingTime / 1000);
}
else if (estimatedRemainingTime < 3600000)
{
int minutes = estimatedRemainingTime / 60000;
int seconds = (estimatedRemainingTime % 60000) / 1000;
timeStr = QString("%1分%2秒").arg(minutes).arg(seconds);
}
else
{
int hours = estimatedRemainingTime / 3600000;
int minutes = (estimatedRemainingTime % 3600000) / 60000;
timeStr = QString("%1小时%2分").arg(hours).arg(minutes);
}
outlog(QString("平均处理时间: %1ms").arg(avgTime));
outlog(QString("预计剩余时间: %1").arg(timeStr));
}
outlog("-------------------");
}
if (!m_rstParser.save(outputFilePath, rstInfoList))
{
outlog("[错误] 保存翻译后的文件失败");
return false;
}
// 计算总耗时
int totalTime = startTime.msecsTo(QTime::currentTime());
QString totalTimeStr;
if (totalTime < 1000)
{
totalTimeStr = QString("%1毫秒").arg(totalTime);
}
else if (totalTime < 60000)
{
totalTimeStr = QString("%1秒").arg(totalTime / 1000);
}
else if (totalTime < 3600000)
{
int minutes = totalTime / 60000;
int seconds = (totalTime % 60000) / 1000;
totalTimeStr = QString("%1分%2秒").arg(minutes).arg(seconds);
}
else
{
int hours = totalTime / 3600000;
int minutes = (totalTime % 3600000) / 60000;
totalTimeStr = QString("%1小时%2分").arg(hours).arg(minutes);
}
outlog("\n=== 翻译任务完成 ===");
outlog("输出文件: " + outputFilePath);
outlog(QString("成功翻译 %1 个段落").arg(rstInfoList.size()));
outlog(QString("总耗时: %1").arg(totalTimeStr));
return errCount == 0 ? true : false;
}
QString RstTranslator::buildPrompt(const QString &content, const PromptInfo &promptInfo)
{
QString fullPrompt;
// 添加聊天前缀
if (!promptInfo.chatPrefix.isEmpty())
{
fullPrompt += promptInfo.chatPrefix + "\n\n";
}
// 添加需要翻译的内容
fullPrompt += content + "\n\n";
// 添加聊天后缀
if (!promptInfo.chatSuffix.isEmpty())
{
fullPrompt += promptInfo.chatSuffix;
}
return fullPrompt;
}
void RstTranslator::outlog(const QString &log)
{
QString formattedLog = QTime::currentTime().toString("[hh:mm:ss] ") + log;
qDebug() << formattedLog;
if (m_logOutput)
{
m_logOutput->appendPlainText(formattedLog);
}
QCoreApplication::processEvents();
}