[REF] base_gengo: misc code improvements made during code review

bzr revid: qdp-launchpad@openerp.com-20120829082647-rzl1btht2xc05ee4
This commit is contained in:
Quentin (OpenERP) 2012-08-29 10:26:47 +02:00
parent 9c0ee11cbb
commit eb5b3f5733
2 changed files with 59 additions and 46 deletions

View File

@ -26,13 +26,13 @@ class res_company(osv.Model):
_name = "res.company"
_inherit = "res.company"
_columns = {
"gengo_private_key": fields.text("Gengo private key"),
"gengo_public_key": fields.text("Gengo public key"),
"gengo_private_key": fields.text("Gengo Private Key"),
"gengo_public_key": fields.text("Gengo Public Key"),
"gengo_tier": fields.selection([('machine', 'Machine'),
('standard', 'Standard'),
('pro', 'Pro'),
('ultra', 'Ultra')], "Tier Type", required=True),
"gengo_comment": fields.text("Comments"),
"gengo_comment": fields.text("Comments", help="This comment will be automatically be enclosed in each an every request sent to Gengo"),
"gengo_auto_approve": fields.boolean("Auto Approve Translation ?", help="Jobs are Automatically Approved by Gengo."),
}

View File

@ -33,6 +33,8 @@ import time
_logger = logging.getLogger(__name__)
GENGO_DEFAULT_LIMIT = 20
LANG_CODE_MAPPING = {
'ar_SA': ('ar', 'Arabic'),
'id_ID': ('id', 'Indonesian'),
@ -56,14 +58,14 @@ LANG_CODE_MAPPING = {
}
CRON_VALS = {
'name': 'Gengo Sync',
'name': _('Synchronization with Gengo'),
'active': True,
'interval_number': 20,
'interval_type': 'minutes',
'numbercall': -1,
'model': "'base.update.translations'",
'function': "",
'args': "'(20,)'",
'args': "'(20,)'",#not sure
}
@ -75,11 +77,11 @@ class base_update_translation(osv.osv_memory):
def gengo_authentication(self, cr, uid, context=None):
''' To Send Request and Get Response from Gengo User needs Public and Private
key for that user need to sign up to gengo and get public and private
key which is provided by gengo to authentic user '''
key which is provided by gengo to authenticate user '''
user = self.pool.get('res.users').browse(cr, uid, uid, context)
user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
if not user.company_id.gengo_public_key or not user.company_id.gengo_private_key:
return (False, " - Invalid gengo configuration, Either Gengo authentication `Public Key` or `Private Key` is missing. Complete Gengo authentication parameter under `Settings > Companies > Gengo Parameters`.")
return (False, _(" - Invalid Gengo configuration. Gengo authentication `Public Key` or `Private Key` is missing. Complete Gengo authentication parameters under `Settings > Companies > Gengo Parameters`."))
try:
gengo = MyGengo(
public_key=user.company_id.gengo_public_key.encode('ascii'),
@ -89,24 +91,32 @@ class base_update_translation(osv.osv_memory):
gengo.getAccountStats()
return (True, gengo)
except Exception, e:
return (False, "Gengo Connection Error\n%s"%e)
return (False, _("Gengo Connection Error\n%s") %e)
def pack_jobs_request(self, cr, uid, term_ids, context=None):
''' prepare the terms that will be requested to gengo and returns them in a dictionary with following format
{'jobs': {
'term1.id': {...}
'term2.id': {...}
}
}'''
def pack_jobs_request(self, cr, uid, term_ids, context):
jobs = {}
gengo_parameter_pool = self.pool.get('res.users').browse(cr, uid, uid, context)
translation_pool = self.pool.get('ir.translation')
auto_approve = gengo_parameter_pool.company_id.gengo_auto_approve and 1 or 0
for term in translation_pool.browse(cr, uid, term_ids, context):
jobs = {}
user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
auto_approve = 1 if user.company_id.gengo_auto_approve or 0
for term in translation_pool.browse(cr, uid, term_ids, context=context):
if re.search(r"\w", term.src or ""):
job = {'type': 'text',
jobs[term.id] = {'type': 'text',
'slug': 'single::English to ' + LANG_CODE_MAPPING[term.lang][1],
'tier': tools.ustr(gengo_parameter_pool.company_id.gengo_tier),
'tier': tools.ustr(user.company_id.gengo_tier),
#'tier': tools.ustr(term.gengo_tier),
'body_src': term.src,
'lc_src': 'en',
'lc_tgt': LANG_CODE_MAPPING[term.lang][0],
'auto_approve': auto_approve,
'comment': gengo_parameter_pool.company_id.gengo_comment}
jobs.update({term.id: job})
'comment': gengo_parameter_pool.company_id.gengo_comment,
}
return {'jobs': jobs}
def check_lang_support(self, cr, uid, langs, context=None):
@ -115,35 +125,38 @@ class base_update_translation(osv.osv_memory):
if not flag:
return []
else:
user = self.pool.get('res.users').browse(cr, uid, uid, context)
user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
tier = user.company_id.gengo_tier
if tier == "machine":
tier = "nonprofit"
lang_pair = gengo.getServiceLanguagePairs(lc_src='en')
#print "tier", tier
if lang_pair['opstat'] == 'ok':
for g_lang in lang_pair['response']:
#print 'g_lang', g_lang['lc_tgt'], g_lang['tier']
for l in langs:
if LANG_CODE_MAPPING[l][0] == g_lang['lc_tgt'] and g_lang['tier'] == tier:
new_langs.append(l)
return list(set(new_langs))
def _update_terms(self, cr, uid, response, tier, context):
def _update_terms(self, cr, uid, response, tier, context=None):
translation_pool = self.pool.get('ir.translation')
for jobs in response['jobs']:
for jobs in response['jobs']:
for t_id, res in jobs.items():
vals = {}
if tier == "machine":
vals.update({'value': res['body_tgt'], 'state': 'translated'})
else:
vals.update({'job_id': res['job_id'], 'state': 'inprogress'})
translation_pool.write(cr, uid, [t_id], vals, context)
translation_pool.write(cr, uid, [t_id], vals, context=context)
return
def _send_translation_terms(self, cr, uid, term_ids, context):
def _send_translation_terms(self, cr, uid, term_ids, context=None):
"""
Lazy Polling will be perform when user or cron request for the translation.
"""
user = self.pool.get('res.users').browse(cr, uid, uid, context)
user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
flag, gengo = self.gengo_authentication(cr, uid, context)
if flag:
request = self.pack_jobs_request(cr, uid, term_ids, context)
@ -170,33 +183,33 @@ class base_update_translation(osv.osv_memory):
context = {}
lang_pool = self.pool.get('res.lang')
super(base_update_translation, self).act_update(cr, uid, ids, context)
msg = "1. Translation file loaded successfully.\n2. Processing Gengo Translation:\n"
msg = _("1. Translation file loaded successfully.\n2. Processing Gengo Translation:\n")
flag, gengo = self.gengo_authentication(cr, uid, context)
if not flag:
msg += gengo
else:
for res in self.browse(cr, uid, ids, context):
for res in self.browse(cr, uid, ids, context=context):
lang_id = lang_pool.search(cr, uid, [('code', '=', res.lang)])
lang_name = self._get_lang_name(cr, uid, res.lang)
try:
if LANG_CODE_MAPPING[res.lang][0]:
lang_search = lang_pool.search(cr, uid, [('gengo_sync', '=', True), ('id', '=', lang_id[0])])
if lang_search:
msg += ' - This language `%s` is already in queue for translation.' % (lang_name)
msg += _(' - This language `%s` is already in queue for translation.') % (lang_name)
else:
msg += ' - The language `%s` is queued for translation through Gengo translation.' % (lang_name)
msg += _(' - The language `%s` is queued for translation through Gengo translation.') % (lang_name)
lang_pool.write(cr, uid, lang_id, {'gengo_sync': True})
_logger.info('Translation request for language `%s` has been queued successfully.', lang_name)
self.do_check_schedular(cr, uid, 'gengo_sync_send_request_scheduler', 'Gengo Sync Translation (Request)', '_sync_request', context)
self.do_check_schedular(cr, uid, 'gengo_sync_receive_request_scheduler', 'Gengo Sync Translation (Response)', '_sync_response', context)
self._sync_request(cr, uid, limit=20)
self.do_check_schedular(cr, uid, 'gengo_sync_send_request_scheduler', _('Gengo Sync Translation (Request)'), '_sync_request', context)
self.do_check_schedular(cr, uid, 'gengo_sync_receive_request_scheduler', _('Gengo Sync Translation (Response)'), '_sync_response', context)
self._sync_request(cr, uid, limit=GENGO_DEFAULT_LIMIT)
except:
msg +=' - The Language `%s` is not supported by Gengo Traditional Service.'%(lang_name)
msg += _(' - The Language `%s` is not supported by Gengo Traditional Service.') % (lang_name)
context.update({'message': msg})
obj_model = self.pool.get('ir.model.data')
model_data_ids = obj_model.search(cr, uid, [('model', '=', 'ir.ui.view'), ('name', '=', 'update_translation_wizard_view_confirm')])
view_id = obj_model.read(cr, uid, model_data_ids, fields=['res_id'], context=context)[0]['res_id']
context.update({'message': msg})
return {
'view_type': 'form',
'view_mode': 'form',
@ -207,7 +220,7 @@ class base_update_translation(osv.osv_memory):
'context': context,
}
def _sync_response(self, cr, uid, limit=20, context=None):
def _sync_response(self, cr, uid, limit=GENGO_DEFAULT_LIMIT, context=None):
"""
This method will be call by cron services to get translation from
gengo for translation terms which are posted to be translated. It will
@ -226,7 +239,7 @@ class base_update_translation(osv.osv_memory):
vals={}
job_response = gengo.getTranslationJob(id=term.job_id)
if job_response['opstat'] != 'ok':
_logger.warning("Invalid Response! Skipping translation Terms with `id` %s."%(term.job_id))
_logger.warning("Invalid Response! Skipping translation Terms with `id` %s." % (term.job_id))
continue
if job_response['response']['job']['status'] == 'approved':
vals.update({'state': 'translated',
@ -237,27 +250,27 @@ class base_update_translation(osv.osv_memory):
if job_comment['opstat']=='ok':
gengo_comments=""
for comment in job_comment['response']['thread']:
gengo_comments+='%s Commented on %s by %s. \n'%(comment['body'], time.ctime(comment['ctime']), comment['author'])
vals.update({'gengo_comment':gengo_comments})
gengo_comments += _('%s Commented on %s by %s. \n') %(comment['body'], time.ctime(comment['ctime']), comment['author'])
vals.update({'gengo_comment': gengo_comments})
up_comment +=1
if vals:
translation_pool.write(cr, uid, term.id,vals)
_logger.info("Successfully Updated `%d` terms and Comments for `%d` terms."%(up_term, up_comment ))
_logger.info("Successfully Updated `%d` terms and Comments for `%d` terms." % (up_term, up_comment ))
return True
def _sync_request(self, cr, uid, limit=20, context=None):
"""
This scheduler will send a job request to the gengo , which terms are
in translate state and gengo_translation is true
"""
def _sync_request(self, cr, uid, limit=GENGO_DEFAULT_LIMIT, context=None):
"""This scheduler will send a job request to the gengo , which terms are
waiing to be translated and for which gengo_translation is True"""
if context is None:
context = {}
language_pool = self.pool.get('res.lang')
translation_pool = self.pool.get('ir.translation')
try:
lang_ids = language_pool.search(cr, uid, [('gengo_sync', '=', True)])
langs = [lang.code for lang in language_pool.browse(cr, uid, lang_ids)]
langs = self.check_lang_support(cr, uid, langs)
lang_ids = language_pool.search(cr, uid, [('gengo_sync', '=', True)]) #really? what's the point not checking ALL the languages if gengo support it? i feel like it's aunecessary load for the user that must configure yet another thing
langs = [lang.code for lang in language_pool.browse(cr, uid, lang_ids, context=context)]
#print "LANGS 1", langs
langs = self.check_lang_support(cr, uid, langs, context=context)#must move
#print "LANGS 2", langs
term_ids = translation_pool.search(cr, uid, [('state', '=', 'to_translate'), ('gengo_translation', '=', True), ('lang', 'in', langs)], limit=limit)
if term_ids:
self._send_translation_terms(cr, uid, term_ids, context)