Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/moses-smt/mosesdecoder.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
path: root/mingw
diff options
context:
space:
mode:
authorJeroen Vermeulen <jtv@precisiontranslationtools.com>2015-05-17 14:27:13 +0300
committerJeroen Vermeulen <jtv@precisiontranslationtools.com>2015-05-17 14:27:13 +0300
commit262edf25115fee37028de70d24281e4b73416be5 (patch)
tree22cbd4d5931c7237ee2c3e6fb28629aa8f04dd44 /mingw
parent07a8fe06aacb91b3d37ba13ba635fc6bec4e1b6b (diff)
Fix more python lint.
Diffstat (limited to 'mingw')
-rw-r--r--mingw/MosesGUI/datamodel.py311
-rw-r--r--mingw/MosesGUI/engine.py93
-rw-r--r--mingw/MosesGUI/moses.py38
-rw-r--r--mingw/MosesGUI/util.py16
4 files changed, 302 insertions, 156 deletions
diff --git a/mingw/MosesGUI/datamodel.py b/mingw/MosesGUI/datamodel.py
index 570649ee5..ad802e439 100644
--- a/mingw/MosesGUI/datamodel.py
+++ b/mingw/MosesGUI/datamodel.py
@@ -1,15 +1,37 @@
# -*- coding: utf-8 -*-
-from PyQt4.QtCore import *
-from PyQt4.QtSql import *
+from PyQt4.QtCore import (
+ QDateTime,
+ SIGNAL,
+ )
+from PyQt4.QtGui import (
+ QMessageBox,
+ )
+from PyQt4.QtSql import (
+ QSqlDatabase,
+ QSqlQuery,
+ QSqlTableModel,
+ QVariant,
+ )
+
+import ConfigParser
+import os
+import shutil
+import sys
+import threading
+import urllib2
+import zipfile
+
+from util import (
+ doAlert,
+ doQuestion,
+ )
-import sys, os, threading, time, urllib2, zipfile, shutil, ConfigParser
-from util import *
class DataModel(QSqlTableModel):
- import os
- defaultDbFile = os.path.join(os.path.split(os.path.realpath(__file__))[0], "models.sqlite")
-
+ defaultDbFile = os.path.join(
+ os.path.split(os.path.realpath(__file__))[0], "models.sqlite")
+
def __init__(self, parent=None, filename=None):
self.installThreads = {}
self.processes = set()
@@ -19,29 +41,51 @@ class DataModel(QSqlTableModel):
print >> sys.stderr, "Open database at %s" % filename
self.db.setDatabaseName(filename)
self.db.open()
- query = QSqlQuery('SELECT COUNT(*) FROM sqlite_master WHERE type="table" AND tbl_name="models"', self.db)
+ query = QSqlQuery(
+ 'SELECT COUNT(*) '
+ 'FROM sqlite_master '
+ 'WHERE type="table" AND tbl_name="models"',
+ self.db)
if not query.next() or query.value(0).toInt()[0] < 1:
- #create new table
+ # Create new table.
print >> sys.stderr, "Table not find, create the table"
- query = QSqlQuery('CREATE TABLE models (ID INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, status TEXT, srclang TEXT, trglang TEXT, date DATE, path TEXT, mosesini TEXT, origin TEXT, originMode TEXT, deleted TEXT)', self.db)
+ query = QSqlQuery(
+ 'CREATE TABLE models ('
+ 'ID INTEGER PRIMARY KEY AUTOINCREMENT, '
+ 'name TEXT, '
+ 'status TEXT, '
+ 'srclang TEXT, '
+ 'trglang TEXT, '
+ 'date DATE, '
+ 'path TEXT, '
+ 'mosesini TEXT, '
+ 'origin TEXT, '
+ 'originMode TEXT, '
+ 'deleted TEXT)',
+ self.db)
if query.next():
print >> sys.stderr, query.value(0).toString()
- #TODO: shoudn't design the deletion checking like this
- #change all deleted models into not deleted in case it failed last time
- query = QSqlQuery('UPDATE models SET deleted="False" WHERE deleted="True"', self.db)
- query = QSqlQuery('UPDATE models SET status="READY" WHERE status="ON"', self.db)
+ # TODO: shoudn't design the deletion checking like this
+ # Change all deleted models into not deleted in case it failed last
+ # time.
+ query = QSqlQuery(
+ 'UPDATE models SET deleted="False" WHERE deleted="True"', self.db)
+ query = QSqlQuery(
+ 'UPDATE models SET status="READY" WHERE status="ON"', self.db)
super(DataModel, self).__init__(parent, self.db)
self.setTable("models")
self.select()
self.setEditStrategy(QSqlTableModel.OnFieldChange)
-
+
def destroy(self):
bExit = False
for i in self.installThreads:
t, flag = self.installThreads[i]
if t.isAlive() and flag:
if not bExit:
- if not doQuestion("Installing process is running in the background, do you want to terminate them and exit?"):
+ if not doQuestion(
+ "Installing process is running in the background, "
+ "do you want to terminate them and exit?"):
return False
else:
bExit = True
@@ -51,32 +95,37 @@ class DataModel(QSqlTableModel):
self.db.close()
self.db = None
return True
-
+
def getQSqlDatabase(self):
return self.db
-
+
def getRowID(self, row):
record = self.record(row)
return record.value('ID')
-
+
def delModel(self, row):
record = self.record(row)
if str(record.value('deleted').toString()) == 'True':
- self.emit(SIGNAL("messageBox(QString)"), "The model is deleting, please be patient!")
+ self.emit(
+ SIGNAL("messageBox(QString)"),
+ "The model is deleting, please be patient!")
return
- #hint to decide what to delete
+ # Hint to decide what to delete.
text = '''You are going to delete the selected model entry.
Do you also want to delete all the model files on the disk?
Click "Yes" to delete model entry and model files.
Click "No" to delete model entry but keep model files.
Click "Cancel" to do nothing.'''
- reply = QMessageBox.question(None, 'Message', text, QMessageBox.Yes, QMessageBox.No, QMessageBox.Cancel)
-
+ reply = QMessageBox.question(
+ None, 'Message', text, QMessageBox.Yes, QMessageBox.No,
+ QMessageBox.Cancel)
+
if reply == QMessageBox.Cancel:
return
else:
record.setValue('deleted', 'True')
self.changeRecord(row, record)
+
def delModelThread():
irowid, _ = record.value("ID").toInt()
if irowid in self.installThreads:
@@ -88,15 +137,17 @@ Click "Cancel" to do nothing.'''
destDir = str(record.value("path").toString())
try:
shutil.rmtree(destDir)
- except Exception, e:
- self.emit(SIGNAL("messageBox(QString)"), "Failed to remove dir: " + destDir)
+ except Exception as e:
+ self.emit(
+ SIGNAL("messageBox(QString)"),
+ "Failed to remove dir: " + destDir)
print >> sys.stderr, str(e)
self.removeRow(row)
- #end of Model deleting thread
-
+ # End of Model deleting thread.
+
t = threading.Thread(target=delModelThread)
t.start()
-
+
def newEntry(self):
import random
rec = self.record()
@@ -104,22 +155,22 @@ Click "Cancel" to do nothing.'''
rec.setValue(i, QVariant(str(random.random())))
self.insertRecord(-1, rec)
doAlert(self.query().lastInsertId().toString())
-
+
def changeRecord(self, curRow, record):
- #self.emit(SIGNAL("recordUpdated(bool)"), True) #record selection
+ # self.emit(SIGNAL("recordUpdated(bool)"), True) #record selection
self.setRecord(curRow, record)
- #self.emit(SIGNAL("recordUpdated(bool)"), False) #restore selection
-
+ # self.emit(SIGNAL("recordUpdated(bool)"), False) #restore selection
+
def installModel(self, installParam):
dest = installParam['dest']
- #make dir
+ # Make dir.
if not os.path.exists(dest):
try:
os.makedirs(str(dest))
except:
doAlert("Failed to create install directory: %s" % dest)
return
- #create entry in db
+ # Create entry in db.
rec = self.record()
rec.setValue('name', installParam['modelName'])
rec.setValue('status', 'Fetching Source...')
@@ -130,76 +181,89 @@ Click "Cancel" to do nothing.'''
rec.setValue('deleted', 'False')
self.insertRecord(-1, rec)
rowid = self.query().lastInsertId()
-
- #start thread
+
+ # Start thread.
def installThread(irowid):
-
- #find the current row in model
+
+ # Find the current row in model.
def updateRecord(keyvalues):
curRow = None
- for i in xrange(0, self.rowCount()): # TODO: use binary search instead of linear
+ # TODO: use binary search instead of linear
+ for i in xrange(0, self.rowCount()):
if self.record(i).value("ID") == rowid:
curRow = i
break
- if not curRow is None:
+ if curRow is not None:
record = self.record(curRow)
for key in keyvalues:
record.setValue(key, keyvalues[key])
self.changeRecord(curRow, record)
return curRow
-
+
def checkExit():
- if not irowid in self.installThreads or not self.installThreads[irowid][1]: #check thread is ok to run
+ # Check thread is ok to run.
+ if irowid not in self.installThreads or not self.installThreads[irowid][1]:
return True
else:
return False
-
+
def markExit():
- if irowid in self.installThreads: #set thread to dead
+ if irowid in self.installThreads: # Set thread to dead.
self.installThreads[irowid][1] = False
-
- def statusMessageLogMarkExit(status=None, message=None, exception=None):
- if not status is None:
- updateRecord({'status':status})
- if not message is None:
+
+ def statusMessageLogMarkExit(status=None, message=None,
+ exception=None):
+ if status is not None:
+ updateRecord({'status': status})
+ if message is not None:
self.emit(SIGNAL("messageBox(QString)"), message)
print >> sys.stderr, message
- if not exception is None:
+ if exception is not None:
print >> sys.stderr, str(exception)
markExit()
-
- #1. download or copy from local
- destFile = os.path.join(str(dest), "model.zip") #where the downloaded/copied zip file is
- destDir = os.path.join(str(dest), "model") #where the unzipped contents are
-
+
+ # 1. Download or copy from local.
+ # Where the downloaded/copied zip file is:
+ destFile = os.path.join(str(dest), "model.zip")
+ # Where the unzipped contents are:
+ destDir = os.path.join(str(dest), "model")
+
if installParam['sourceMode'] == 'Local':
fin = fout = None
try:
inFile = str(installParam['source'])
total_size = os.path.getsize(inFile)
fin = open(inFile, 'rb')
- chunk_size = 52428800 #50MB as chunk size
+ chunk_size = 52428800 # 50MB as chunk size
fout = open(destFile, 'wb')
content = fin.read(chunk_size)
download_size = content_size = len(content)
lastMsg = ""
while content_size > 0:
- if checkExit(): #check if thread is notified as exit
+ # Check if thread is notified as exit.
+ if checkExit():
return statusMessageLogMarkExit()
fout.write(content)
if total_size > 0:
- msg = 'COPY %.0f%%' % (download_size * 100.0 / total_size)
+ msg = 'COPY %.0f%%' % (
+ download_size * 100.0 / total_size)
else:
msg = 'COPY %d MB' % (download_size/1048576)
- if msg <> lastMsg:
- updateRecord({'status' : msg})
+ if msg != lastMsg:
+ updateRecord({'status': msg})
lastMsg = msg
content = fin.read(chunk_size)
content_size = len(content)
download_size += content_size
- except Exception, e:
- return statusMessageLogMarkExit(status='Failed copying from: %s' % installParam['source'],
- message="Failed copy model: %s" % installParam['modelName'], exception=e)
+ except Exception as e:
+ return statusMessageLogMarkExit(
+ status=(
+ 'Failed copying from: %s'
+ % installParam['source']),
+ message=(
+ "Failed copy model: %s"
+ % installParam['modelName']),
+ exception=e)
finally:
if fin:
fin.close()
@@ -211,46 +275,63 @@ Click "Cancel" to do nothing.'''
try:
conn = urllib2.urlopen(str(installParam['source']))
total_size = int(conn.headers['Content-Length'])
- chunk_size = 1048576 #1MB as chunk size
+ chunk_size = 1048576 # 1MB as chunk size
fout = open(destFile, 'wb')
content = conn.read(chunk_size)
download_size = content_size = len(content)
lastMsg = ""
while content_size > 0:
- if checkExit(): #check if thread is notified as exit
+ # Check if thread is notified as exit.
+ if checkExit():
return statusMessageLogMarkExit()
fout.write(content)
if total_size > 0:
- msg = 'DOWNLOAD %.0f%%' % (download_size * 100.0 / total_size)
+ msg = 'DOWNLOAD %.0f%%' % (
+ download_size * 100.0 / total_size)
else:
msg = 'DOWNLOAD %d MB' % (download_size/1048576)
- if msg <> lastMsg:
- updateRecord({'status' : msg})
+ if msg != lastMsg:
+ updateRecord({'status': msg})
lastMsg = msg
content = conn.read(chunk_size)
content_size = len(content)
download_size += content_size
- except Exception, e:
- return statusMessageLogMarkExit(status='Failed downloading from: %s' % installParam['source'],
- message="Failed download model: %s" % installParam['modelName'], exception=e)
+ except Exception as e:
+ return statusMessageLogMarkExit(
+ status=(
+ 'Failed downloading from: %s'
+ % installParam['source']),
+ message=(
+ "Failed download model: %s"
+ % installParam['modelName']),
+ exception=e)
finally:
if conn:
conn.close()
if fout:
fout.close()
else:
- return statusMessageLogMarkExit(status='Unsupported source mode: %s' % installParam['sourceMode'])
-
- #2. unzip
+ return statusMessageLogMarkExit(
+ status='Unsupported source mode: %s'
+ % installParam['sourceMode'])
+
+ # 2. Unzip.
zfile = fout = None
try:
zfile = zipfile.ZipFile(destFile)
- #check property files
- if not "model.ini" in zfile.namelist():
- return statusMessageLogMarkExit(status='Missing model.ini in model file: %s' % installParam['sourceMode'],
- message="Invalid modle file format because model.ini is missing in the zipped model file, exit installation for model %s" % installParam['modelName'])
- chunk_size = 52428800 #50MB as chunk size
- #get file size uncompressed
+ # Check property files.
+ if "model.ini" not in zfile.namelist():
+ return statusMessageLogMarkExit(
+ status=(
+ 'Missing model.ini in model file: %s'
+ % installParam['sourceMode']),
+ message=(
+ "Invalid modle file format because model.ini "
+ "is missing in the zipped model file, exit "
+ "installation for model %s"
+ % installParam['modelName']))
+ chunk_size = 52428800 # 50MB as chunk size
+ # Get file size uncompressed.
total_size = 0
for name in zfile.namelist():
total_size += zfile.getinfo(name).file_size
@@ -269,24 +350,31 @@ Click "Cancel" to do nothing.'''
content_size = len(content)
download_size += content_size
while content_size > 0:
- if checkExit(): #check if thread is notified as exit
+ # Check if thread is notified as exit.
+ if checkExit():
return statusMessageLogMarkExit()
fout.write(content)
if total_size > 0:
- msg = 'UNZIP %.0f%%' % (download_size * 100.0 / total_size)
+ msg = 'UNZIP %.0f%%' % (
+ download_size * 100.0 / total_size)
else:
- msg = 'UNZIP %d MB' % (download_size/1048576)
- if msg <> lastMsg:
- updateRecord({'status' : msg})
+ msg = 'UNZIP %d MB' % (
+ download_size/1048576)
+ if msg != lastMsg:
+ updateRecord({'status': msg})
lastMsg = msg
content = fin.read(chunk_size)
content_size = len(content)
download_size += content_size
fin.close()
fout.close()
- except Exception, e:
- return statusMessageLogMarkExit(status='Failed unzipping from: %s' % installParam['source'],
- message="Failed unzip model: %s" % installParam['modelName'], exception=e)
+ except Exception as e:
+ return statusMessageLogMarkExit(
+ status=(
+ 'Failed unzipping from: %s' % installParam['source']),
+ message=(
+ "Failed unzip model: %s" % installParam['modelName']),
+ exception=e)
finally:
if zfile:
zfile.close()
@@ -294,32 +382,43 @@ Click "Cancel" to do nothing.'''
fin.close()
if fout:
fout.close()
-
- #3 post process and check data validity
+
+ # 3 Post process and check data validity.
try:
modelini = os.path.join(destDir, "model.ini")
cp = ConfigParser.RawConfigParser()
- cp.read(modelini)
+ cp.read(modelini)
mosesini = os.path.join(destDir, 'moses.ini')
if not os.path.exists(mosesini):
- raise Exception, "Moses ini doesn't exist"
- updateRecord({'srclang':cp.get("Language", 'Source Language').upper(), 'trglang':cp.get("Language", 'Target Language').upper(), 'mosesini':mosesini})
- except Exception, e:
- return statusMessageLogMarkExit(status='ERROR model format %s' % installParam['source'],
- message="Unspported model format: %s" % installParam['modelName'], exception=e)
-
- statusMessageLogMarkExit(status='READY', message="Model %s Installed!" % installParam['modelName'])
- #send new model signal
- self.emit(SIGNAL("modelInstalled()")) #record selection
+ raise Exception("Moses ini doesn't exist")
+ updateRecord({
+ 'srclang': cp.get("Language", 'Source Language').upper(),
+ 'trglang': cp.get("Language", 'Target Language').upper(),
+ 'mosesini': mosesini},
+ )
+ except Exception as e:
+ return statusMessageLogMarkExit(
+ status='ERROR model format %s' % installParam['source'],
+ message=(
+ "Unspported model format: %s"
+ % installParam['modelName']),
+ exception=e)
+
+ statusMessageLogMarkExit(
+ status='READY',
+ message="Model %s Installed!" % installParam['modelName'])
+ # Send new model signal.
+ self.emit(SIGNAL("modelInstalled()")) # Record selection.
return
- #end of thread func
-
- #start the thread
+ # End of thread func.
+
+ # Start the thread.
irowid, _ = rowid.toInt()
t = threading.Thread(target=installThread, args=(irowid, ))
- if irowid in self.installThreads: #if old thread is there
- print >> sys.stderr, "table rowid %d already has a thread running, stop it" % irowid
+ if irowid in self.installThreads: # If old thread is there.
+ print >> sys.stderr, (
+ "table rowid %d already has a thread running, stop it"
+ % irowid)
self.installThreads[irowid][1] = False
self.installThreads[irowid] = [t, True]
t.start()
-
diff --git a/mingw/MosesGUI/engine.py b/mingw/MosesGUI/engine.py
index eb0226f55..012ed06ba 100644
--- a/mingw/MosesGUI/engine.py
+++ b/mingw/MosesGUI/engine.py
@@ -1,11 +1,17 @@
# -*- coding: utf-8 -*-
-from PyQt4.QtCore import *
+import ConfigParser
+import os
+import subprocess
+import sys
-import os, subprocess, sys, signal, ConfigParser
+from PyQt4.QtCore import (
+ QObject,
+ SIGNAL,
+ )
+
+from util import doAlert
-from moses import Moses
-from util import *
class Engine(QObject):
def __init__(self, model, moses):
@@ -13,72 +19,93 @@ class Engine(QObject):
self.model = model
self.moses = moses
self.check(self.model)
- #determine how many steps by num of modules in the model directory (moses + tok/detok + ...) + 1
+ # Determine how many steps by num of modules in the model directory
+ # (moses + tok/detok + ...) + 1
modelini = model['path'] + os.sep + 'model' + os.sep + 'model.ini'
if not os.path.exists(modelini):
- raise Exception, "Model ini file doesn't exist, please check model dir %s" % modelini
+ raise Exception(
+ "Model ini file doesn't exist, please check model dir %s"
+ % modelini)
cp = ConfigParser.RawConfigParser()
cp.readfp(open(modelini))
- #true model
truemodel = None
try:
truemodel = cp.get("Preprocess", 'Truemodel')
- if not os.path.exists(model['path'] + os.sep + 'model' + os.sep + truemodel):
+ truemodel_path = os.path.join(model['path'], 'model', truemodel)
+ if not os.path.exists(truemodel_path):
doAlert("Truemodel doesn't exist, ignore %s" % truemodel)
truemodel = None
- except:
- #doAlert("Truemodel not configured")
+ except:
+ # doAlert("Truemodel not configured")
truemodel = None
self.cmds = []
- #tok
- self.cmds.append('"%s" -q -l %s -noxml' % (self.moses.getTokenizer(), str(model['srclang']).lower()))
- if not truemodel is None:
- self.cmds.append('"%s" -model "%s"' % (self.moses.getTruecase(), truemodel) )
+ # tok
+ self.cmds.append(
+ '"%s" -q -l %s -noxml'
+ % (self.moses.getTokenizer(), str(model['srclang']).lower()))
+ if truemodel is not None:
+ self.cmds.append(
+ '"%s" -model "%s"' % (self.moses.getTruecase(), truemodel))
self.cmds.append('"%s" -f moses.ini' % self.moses.getMosesCmd())
self.cmds.append('"%s"' % self.moses.getDetruecase())
- self.cmds.append('"%s" -q -noxml -l %s' % (self.moses.getDetokenizer(), str(model['trglang']).lower()))
+ self.cmds.append(
+ '"%s" -q -noxml -l %s'
+ % (self.moses.getDetokenizer(), str(model['trglang']).lower()))
self.process = []
- #doAlert('\n'.join(self.cmds))
-
+ # doAlert('\n'.join(self.cmds))
+
def check(self, model):
- if not os.path.exists(model['path']) or not os.path.exists(model['mosesini']):
- raise Exception, "Model file doesn't exist, please check model dir %s" % self.model['path']
-
+ model_path_exists = os.path.exists(model['path'])
+ model_mosesini_exists = os.path.exists(model['mosesini'])
+ if not model_path_exists or not model_mosesini_exists:
+ raise Exception(
+ "Model file doesn't exist, please check model dir %s"
+ % self.model['path'])
+
def countSteps(self):
return len(self.cmds) + 1
-
+
def start(self):
- #print >> sys.stderr, self.cmds
+ # print >> sys.stderr, self.cmds
try:
self.emit(SIGNAL("stepFinished(int)"), 0)
for i, cmd in enumerate(self.cmds):
- proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, cwd=os.path.join(str(self.model['path']), 'model'))
+ proc = subprocess.Popen(
+ cmd, shell=True, stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ cwd=os.path.join(str(self.model['path']), 'model'))
self.process.append(proc)
if not proc.poll() is None:
- raise Exception, "Failed to start engine!"
+ raise Exception("Failed to start engine!")
proc.stdin.write("dummy\n")
proc.stdin.flush()
if len(proc.stdout.readline().strip()) <= 0:
- raise Exception, "Engine process exited: [%s] in folder [%s]" % (cmd, os.path.join(str(self.model['path']), 'model'))
- self.emit(SIGNAL("stepFinished(int)"), i+1)
+ raise Exception(
+ "Engine process exited: [%s] in folder [%s]"
+ % (
+ cmd,
+ os.path.join(str(self.model['path']), 'model')))
+ self.emit(SIGNAL("stepFinished(int)"), i + 1)
self.emit(SIGNAL("loaded(bool, QString)"), True, "Model Loaded")
- except Exception, e:
- self.emit(SIGNAL("loaded(bool, QString)"), False, "Failed to load Model: %s" % str(e))
-
+ except Exception as e:
+ self.emit(
+ SIGNAL("loaded(bool, QString)"), False,
+ "Failed to load Model: %s" % str(e))
+
def stop(self):
for process in self.process:
- #doAlert(str(process.pid))
- #print >> sys.stderr, str(process)
+ # doAlert(str(process.pid))
+ # print >> sys.stderr, str(process)
process.terminate()
process.wait()
self.process = []
-
+
def translate(self, input):
lastInput = input
try:
for i, proc in enumerate(self.process):
if not proc.poll() is None:
- raise Exception, "Failed to start engine!"
+ raise Exception("Failed to start engine!")
proc.stdin.write("%s\n" % lastInput)
proc.stdin.flush()
output = proc.stdout.readline().strip()
diff --git a/mingw/MosesGUI/moses.py b/mingw/MosesGUI/moses.py
index e26dd32b9..9771893ef 100644
--- a/mingw/MosesGUI/moses.py
+++ b/mingw/MosesGUI/moses.py
@@ -1,20 +1,28 @@
# -*- coding: utf-8 -*-
-import sys, os, platform
+import os
+import platform
+import sys
from PyQt4.QtGui import QFileDialog
-from util import *
+
+from util import (
+ doAlert,
+ doQuestion,
+ )
+
class Moses():
def __init__(self):
pass
-
+
def findRegistryPath(self):
import _winreg
key = None
path = None
try:
reg = _winreg.ConnectRegistry(None, _winreg.HKEY_CURRENT_USER)
- key = _winreg.OpenKey(reg, r'Software\Moses Core Team\MosesDecoder')
+ key = _winreg.OpenKey(
+ reg, r'Software\Moses Core Team\MosesDecoder')
value, type = _winreg.QueryValueEx(key, 'Path')
path = value
except Exception, e:
@@ -24,14 +32,16 @@ class Moses():
if key:
_winreg.CloseKey(key)
return path
-
+
def checkMosesInstall(self):
for func in (self.getMosesCmd, self.getTokenizer, self.getDetokenizer, self.getTruecase, self.getDetruecase):
if not os.path.exists(func()):
- doAlert("Missing executables in Moses installation path [%s], exit." % self.mosesPath)
+ doAlert(
+ "Missing executables in Moses installation path [%s], "
+ "exit." % self.mosesPath)
return False
return True
-
+
def detect(self):
pf = platform.system()
if pf == 'Windows':
@@ -39,9 +49,11 @@ class Moses():
if self.mosesPath:
return self.checkMosesInstall()
else:
- if not doQuestion('Cannot find Moses installation, click "Yes" to manually set the Moses path, click "No" to exit.'):
+ if not doQuestion(
+ 'Cannot find Moses installation, click "Yes" to '
+ 'manually set the Moses path, click "No" to exit.'):
return False
- #if not find, use a dialog
+ # If not found, use a dialog.
startdir = 'C:\\'
if "ProgramFiles(x86)" in os.environ:
startdir = os.environ["ProgramFiles(x86)"]
@@ -62,18 +74,18 @@ class Moses():
else:
doAlert("Platform %s not supported yet" % pf)
return False
-
+
def getMosesCmd(self):
return os.path.join(self.mosesPath, 'moses-cmd.exe')
-
+
def getTokenizer(self):
return os.path.join(self.mosesPath, 'tokenizer.exe')
-
+
def getDetokenizer(self):
return os.path.join(self.mosesPath, 'detokenizer.exe')
def getTruecase(self):
return os.path.join(self.mosesPath, 'truecase.exe')
-
+
def getDetruecase(self):
return os.path.join(self.mosesPath, 'detruecase.exe')
diff --git a/mingw/MosesGUI/util.py b/mingw/MosesGUI/util.py
index 541f16621..c4947d81c 100644
--- a/mingw/MosesGUI/util.py
+++ b/mingw/MosesGUI/util.py
@@ -1,22 +1,30 @@
# -*- coding: utf-8 -*-
-from PyQt4.QtGui import *
import sys
+from PyQt4.QtGui import (
+ QApplication,
+ QMessageBox,
+ )
+
+
def doAlert(text):
msgBox = QMessageBox()
msgBox.setText(text)
msgBox.setWindowTitle("Message")
msgBox.setIcon(QMessageBox.Warning)
msgBox.exec_()
-
+
+
def doQuestion(text):
- reply = QMessageBox.question(None, 'Message', text, QMessageBox.Yes, QMessageBox.No)
+ reply = QMessageBox.question(
+ None, 'Message', text, QMessageBox.Yes, QMessageBox.No)
if reply == QMessageBox.Yes:
return True
else:
return False
-
+
+
if __name__ == '__main__':
app = QApplication(sys.argv)
doAlert("doAlert")