File size: 8,826 Bytes
158b61b |
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 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 |
# -*- coding: utf-8 -*-
"""
Module implementing MainWindow.
"""
from PyQt4.QtCore import (
pyqtSignature,
QObject,
Qt,
SIGNAL,
)
from PyQt4.QtGui import (
QMainWindow,
QMessageBox,
QProgressDialog,
)
import sys
import threading
from Ui_mainWindow import Ui_MainWindow
from addMTModel import AddMTModelDialog
from chooseMTModel import ChooseMTModelDialog
from engine import Engine
from credits import DlgCredits
from util import doAlert
class MainWindow(QMainWindow, Ui_MainWindow):
"""
Class documentation goes here.
"""
def setupUi(self, mainWindow):
super(MainWindow, self).setupUi(mainWindow)
self.tableView.setModel(self.datamodel)
self.tableView.hideColumn(0)
# Change status and keep the column.
QObject.connect(
self.datamodel, SIGNAL("recordUpdated(bool)"),
self.on_datamodel_recordUpdated)
QObject.connect(
self.datamodel, SIGNAL("messageBox(QString)"),
self.on_datamodel_messageBox)
# The response to change model.
for obj in (self.editModelName, self.editSrcLang, self.editTrgLang):
obj.installEventFilter(self)
def __init__(self, parent=None, dm=None, moses=None, workdir=None):
"""
Constructor
"""
QMainWindow.__init__(self, parent)
self.moses = moses
self.datamodel = dm
self.engine = None
self.progress = None
self.workdir = workdir
@pyqtSignature("")
def on_delModelBtn_clicked(self):
"""
Slot documentation goes here.
"""
current = self.tableView.currentIndex()
if not current or current.row() < 0:
return
model_in_use = (
self.engine and
self.datamodel.getRowID(current.row()) == self.engine.model['ID']
)
if model_in_use:
text = (
"The model is still in use, do you want to "
"stop and delete it?\n"
"It might take a while..."
)
reply = QMessageBox.question(
None, 'Message', text, QMessageBox.Yes, QMessageBox.No)
if reply == QMessageBox.No:
return
t = self.stopEngine(self.engine)
t.join()
self.engine = None
self.clearPanel()
self.datamodel.delModel(current.row())
@pyqtSignature("")
def on_newModelBtn_clicked(self):
"""
Slot documentation goes here.
"""
dialog = AddMTModelDialog(self, self.workdir)
if dialog.exec_():
installParam = {
'modelName': dialog.modelName,
'source': dialog.source,
'sourceMode': dialog.sourceMode,
'dest': dialog.dest,
}
self.datamodel.installModel(installParam)
self.tableView.selectRow(self.tableView.model().rowCount() - 1)
# self.datamodel.newEntry()
def on_datamodel_recordUpdated(self, bRecord):
# Deal with the selection changed problem.
try:
if bRecord:
current = self.tableView.currentIndex()
if current and current.row() != -1:
self.curSelection = current.row()
else:
self.curSelection = None
else:
if self.curSelection is not None:
self.tableView.selectRow(self.curSelection)
except Exception, e:
print >> sys.stderr, str(e)
def on_datamodel_messageBox(self, str):
doAlert(str)
def closeEvent(self, event):
# Clear up.
if self.datamodel.destroy():
event.accept()
else:
event.reject()
def eventFilter(self, obj, event):
for obj in (self.editModelName, self.editSrcLang, self.editTrgLang):
if self.gridLayout.indexOf(obj) != -1:
if event.type() == event.MouseButtonPress:
dialog = ChooseMTModelDialog(self, self.datamodel)
if dialog.exec_():
# Get the model.
model = {
'ID': dialog.ID,
'name': dialog.modelName,
'srclang': dialog.srcLang,
'trglang': dialog.trgLang,
'path': dialog.path,
'mosesini': dialog.mosesini,
}
self.startEngine(model)
return True # We handle it here.
return super(MainWindow, self).eventFilter(obj, event)
def stopEngine(self, engine):
# Stop the engine with another thread.
def stopEngineThread():
engine.stop()
t = threading.Thread(target=stopEngineThread)
t.start()
return t
def startEngine(self, model):
self.editModelName.setText(model['name'])
self.editSrcLang.setText(model['srclang'])
self.editTrgLang.setText(model['trglang'])
self.editSrc.setText("")
self.editTrg.setText("")
try:
if self.engine:
self.stopEngine(self.engine)
self.engine = None
# Create engine.
self.engine = Engine(model, self.moses)
# Create progress bar dialog.
if self.progress:
self.progress.close()
self.progress = None
self.progress = QProgressDialog(
"Model: %s" % model['name'], "Cancel", 0,
self.engine.countSteps(), self)
self.progress.setAutoReset(True)
self.progress.setAutoClose(True)
self.progress.setWindowModality(Qt.WindowModal)
self.progress.setWindowTitle('Loading Model...')
QObject.connect(
self.progress, SIGNAL("canceled()"), self.progressCancelled)
self.progress.show()
# Connect engine signal.
QObject.connect(
self.engine, SIGNAL("stepFinished(int)"),
self.engineStepFinished)
QObject.connect(
self.engine, SIGNAL("loaded(bool, QString)"),
self.engineLoaded)
def startEngineThread():
self.engine.start()
t = threading.Thread(target=startEngineThread)
t.start()
except Exception, e:
if self.engine:
self.stopEngine(self.engine)
self.engine = None
self.clearPanel()
doAlert("Error start MT engine: " + str(e))
def clearPanel(self):
if self.engine:
self.stopEngine(self.engine)
self.engine = None
self.editModelName.setText("")
self.editSrcLang.setText("")
self.editTrgLang.setText("")
self.editSrc.setText("")
self.editTrg.setText("")
def progressCancelled(self):
self.clearPanel()
if self.engine:
self.stopEngine(self.engine)
self.engine = None
if self.progress:
self.progress = None
def engineStepFinished(self, nStep):
if self.progress:
self.progress.setValue(nStep)
def engineLoaded(self, success, message):
if not success:
self.clearPanel()
if message:
doAlert(message)
else:
if self.progress:
self.progress.setValue(self.progress.maximum())
self.progress = None
@pyqtSignature("")
def on_btnTranslate_clicked(self):
"""
Slot documentation goes here.
"""
if self.engine is None:
doAlert("Please load MT model first.")
return
self.btnTranslate.setEnabled(False)
self.editTrg.setText("")
try:
texts = str(self.editSrc.toPlainText().toUtf8()).split('\n')
trans = []
for text in texts:
if text.strip() == "":
trans.append(text)
else:
trans.append(
self.engine.translate(
text.replace('\r', ' ').strip()).decode('utf8'))
self.editTrg.setText('\n'.join(trans))
except Exception, e:
print >> sys.stderr, str(e)
doAlert("Translation failed!")
self.btnTranslate.setEnabled(True)
self.btnTranslate.setFocus()
@pyqtSignature("QString")
def on_labelInfo_linkActivated(self, link):
"""
Slot documentation goes here.
"""
dialog = DlgCredits(self)
dialog.exec_()
|