Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

402 linhas
12 KiB

  1. # Copyright (c) 2012 Web Notes Technologies Pvt Ltd (http://erpnext.com)
  2. #
  3. # MIT License (MIT)
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a
  6. # copy of this software and associated documentation files (the "Software"),
  7. # to deal in the Software without restriction, including without limitation
  8. # the rights to use, copy, modify, merge, publish, distribute, sublicense,
  9. # and/or sell copies of the Software, and to permit persons to whom the
  10. # Software is furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  16. # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  17. # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  18. # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  19. # CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
  20. # OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  21. #
  22. from __future__ import unicode_literals
  23. """
  24. Contributing:
  25. 1. Add the .csv file
  26. 2. Run import
  27. 3. Then run translate
  28. """
  29. import webnotes, conf
  30. import os
  31. import codecs
  32. import json
  33. import re
  34. messages = {}
  35. def translate(lang=None):
  36. languages = [lang]
  37. if lang=="all" or lang==None:
  38. languages = get_all_languages()
  39. print "Extracting / updating translatable strings..."
  40. build_message_files()
  41. print "Compiling messages in one file..."
  42. export_messages(lang, '_lang_tmp.csv')
  43. for lang in languages:
  44. if lang != "en":
  45. filename = 'app/translations/'+lang+'.csv'
  46. print "For " + lang + ":"
  47. print "Translating via Google Translate..."
  48. google_translate(lang, '_lang_tmp.csv', filename)
  49. print "Updating language files..."
  50. import_messages(lang, filename)
  51. print "Deleting temp file..."
  52. os.remove('_lang_tmp.csv')
  53. def get_all_languages():
  54. return [f[:-4] for f in os.listdir("app/translations") if f.endswith(".csv")]
  55. def update_translations():
  56. """
  57. compare language file timestamps with last updated timestamps in `.wnf-lang-status`
  58. if timestamps are missing / changed, build new `.json` files in the `lang folders`
  59. """
  60. langstatus = {}
  61. languages = get_all_languages()
  62. message_updated = False
  63. status_file_path = "app/.wnf-lang-status"
  64. if os.path.exists(status_file_path):
  65. with open(status_file_path, "r") as langstatusfile:
  66. langstatus = eval(langstatusfile.read())
  67. for lang in languages:
  68. filename = 'app/translations/'+lang+'.csv'
  69. if langstatus.get(lang, None)!=os.path.getmtime(filename):
  70. print "Setting up lang files for " + lang + "..."
  71. if not message_updated:
  72. print "Extracting / updating translatable strings..."
  73. build_message_files()
  74. message_updated = True
  75. print "Writing translations..."
  76. import_messages(lang, filename)
  77. langstatus[lang] = os.path.getmtime(filename)
  78. with open(status_file_path, "w") as langstatusfile:
  79. langstatus = langstatusfile.write(str(langstatus))
  80. def build_message_files():
  81. """build from doctypes, pages, database and framework"""
  82. if not webnotes.conn:
  83. webnotes.connect()
  84. build_for_pages('lib/core')
  85. build_for_pages('app')
  86. build_from_doctype_code('lib/core')
  87. build_from_doctype_code('app')
  88. # doctype
  89. build_from_database()
  90. build_for_framework('lib/webnotes', 'py', with_doctype_names=True)
  91. build_for_framework('lib/public/js/wn', 'js')
  92. build_for_framework('app/public/js', 'js', with_doctype_names=True)
  93. #build_for_modules()
  94. def build_for_pages(path):
  95. """make locale files for framework py and js (all)"""
  96. messages = []
  97. for (basepath, folders, files) in os.walk(path):
  98. if os.path.basename(os.path.dirname(basepath))=="page":
  99. messages_js, messages_py = [], []
  100. for fname in files:
  101. if fname.endswith('.js'):
  102. messages_js += get_message_list(os.path.join(basepath, fname))
  103. if fname.endswith('.py'):
  104. messages_py += get_message_list(os.path.join(basepath, fname))
  105. if messages_js:
  106. write_messages_file(basepath, messages_js, "js")
  107. if messages_py:
  108. write_messages_file(basepath, messages_py, "py")
  109. def build_for_modules():
  110. """doctype descriptions, module names, etc for each module"""
  111. from webnotes.modules import get_module_path, get_doc_path
  112. for m in webnotes.conn.sql("""select name from `tabModule Def`"""):
  113. module_path = get_module_path(m[0])
  114. if os.path.exists(module_path):
  115. messages = []
  116. messages += [t[0] for t in webnotes.conn.sql("""select description from tabDocType
  117. where module=%s""", m[0])]
  118. for t in webnotes.conn.sql("""select
  119. if(ifnull(title,'')='',name,title)
  120. from tabPage where module=%s
  121. and ifnull(standard,'No')='Yes' """, m[0]):
  122. messages.append(t[0])
  123. messages += [t[0] for t in webnotes.conn.sql("""select t1.name from
  124. tabReport t1, tabDocType t2 where
  125. t1.ref_doctype = t2.name and
  126. t1.is_standard = "Yes" and
  127. t2.module = %s""", m[0])]
  128. doctype_path = get_doc_path(m[0], 'Module Def', m[0])
  129. write_messages_file(doctype_path, messages, 'doc')
  130. def build_from_database():
  131. """make doctype labels, names, options, descriptions"""
  132. def get_select_options(doc):
  133. if doc.doctype=="DocField" and doc.fieldtype=='Select' and doc.options \
  134. and not doc.options.startswith("link:") \
  135. and not doc.options.startswith("attach_files:"):
  136. return doc.options.split('\n')
  137. else:
  138. return []
  139. build_for_doc_from_database(webnotes._dict({
  140. "doctype": "DocType",
  141. "module_field": "module",
  142. "DocType": ["name", "description", "module"],
  143. "DocField": ["label", "description"],
  144. "custom": get_select_options
  145. }))
  146. def build_for_doc_from_database(fields):
  147. from webnotes.modules import get_doc_path
  148. for item in webnotes.conn.sql("""select name from `tab%s`""" % fields.doctype, as_dict=1):
  149. messages = []
  150. doclist = webnotes.bean(fields.doctype, item.name).doclist
  151. for doc in doclist:
  152. if doc.doctype in fields:
  153. messages += map(lambda x: x in fields[doc.doctype] and doc.fields.get(x) or None,
  154. doc.fields.keys())
  155. if fields.custom:
  156. messages += fields.custom(doc)
  157. doc = doclist[0]
  158. if doc.fields.get(fields.module_field):
  159. doctype_path = get_doc_path(doc.fields[fields.module_field],
  160. doc.doctype, doc.name)
  161. write_messages_file(doctype_path, messages, 'doc')
  162. def build_for_framework(path, mtype, with_doctype_names = False):
  163. """make locale files for framework py and js (all)"""
  164. messages = []
  165. for (basepath, folders, files) in os.walk(path):
  166. for fname in files:
  167. if fname.endswith('.' + mtype):
  168. messages += get_message_list(os.path.join(basepath, fname))
  169. # append module & doctype names
  170. if with_doctype_names:
  171. for m in webnotes.conn.sql("""select name, module from `tabDocType`"""):
  172. messages.append(m[0])
  173. messages.append(m[1])
  174. if messages:
  175. write_messages_file(path, messages, mtype)
  176. def build_from_doctype_code(path):
  177. """walk and make locale files in all folders"""
  178. for (basepath, folders, files) in os.walk(path):
  179. messagespy = []
  180. messagesjs = []
  181. for fname in files:
  182. if fname.endswith('py'):
  183. messagespy += get_message_list(os.path.join(basepath, fname))
  184. if fname.endswith('js'):
  185. messagesjs += get_message_list(os.path.join(basepath, fname))
  186. if messagespy:
  187. write_messages_file(basepath, messagespy, 'py')
  188. if messagespy:
  189. write_messages_file(basepath, messagesjs, 'js')
  190. def get_message_list(path):
  191. """get list of messages from a code file"""
  192. import re
  193. messages = []
  194. with open(path, 'r') as sourcefile:
  195. txt = sourcefile.read()
  196. messages += re.findall('_\("([^"]*)"\)', txt)
  197. messages += re.findall("_\('([^']*)'\)", txt)
  198. messages += re.findall('_\("{3}([^"]*)"{3}\)', txt, re.S)
  199. return messages
  200. def write_messages_file(path, messages, mtype):
  201. """write messages to translation file"""
  202. if not os.path.exists(path):
  203. return
  204. if not os.path.exists(os.path.join(path, 'locale')):
  205. os.makedirs(os.path.join(path, 'locale'))
  206. fname = os.path.join(path, 'locale', '_messages_' + mtype + '.json')
  207. messages = list(set(messages))
  208. filtered = []
  209. for m in messages:
  210. if m and re.search('[a-zA-Z]+', m):
  211. filtered.append(m)
  212. with open(fname, 'w') as msgfile:
  213. msgfile.write(json.dumps(filtered, indent=1))
  214. def export_messages(lang, outfile):
  215. """get list of all messages"""
  216. messages = {}
  217. # extract messages
  218. for (basepath, folders, files) in os.walk('.'):
  219. def _get_messages(messages, basepath, mtype):
  220. mlist = get_messages(basepath, mtype)
  221. if not mlist:
  222. return
  223. # update messages with already existing translations
  224. langdata = get_lang_data(basepath, lang, mtype)
  225. for m in mlist:
  226. if not messages.get(m):
  227. messages[m] = langdata.get(m, "")
  228. if os.path.basename(basepath)=='locale':
  229. _get_messages(messages, basepath, 'doc')
  230. _get_messages(messages, basepath, 'py')
  231. _get_messages(messages, basepath, 'js')
  232. # remove duplicates
  233. if outfile:
  234. from csv import writer
  235. with open(outfile, 'w') as msgfile:
  236. w = writer(msgfile)
  237. keys = messages.keys()
  238. keys.sort()
  239. for m in keys:
  240. w.writerow([m.encode('utf-8'), messages.get(m, '').encode('utf-8')])
  241. def import_messages(lang, infile):
  242. """make individual message files for each language"""
  243. data = dict(get_all_messages_from_file(infile))
  244. for (basepath, folders, files) in os.walk('.'):
  245. def _update_lang_file(mtype):
  246. """create a langauge file for the given message type"""
  247. messages = get_messages(basepath, mtype)
  248. if not messages: return
  249. # read existing
  250. langdata = get_lang_data(basepath, lang, mtype)
  251. # update fresh
  252. for m in messages:
  253. if data.get(m):
  254. langdata[m] = data.get(m)
  255. if langdata:
  256. # write new langfile
  257. langfilename = os.path.join(basepath, lang + '-' + mtype + '.json')
  258. with open(langfilename, 'w') as langfile:
  259. langfile.write(json.dumps(langdata, indent=1, sort_keys=True).encode('utf-8'))
  260. #print 'wrote ' + langfilename
  261. if os.path.basename(basepath)=='locale':
  262. # make / update lang files for each type of message file (doc, js, py)
  263. # example: hi-doc.json, hi-js.json, hi-py.json
  264. _update_lang_file('doc')
  265. _update_lang_file('js')
  266. _update_lang_file('py')
  267. def get_doc_messages(module, doctype, name):
  268. from webnotes.modules import get_doc_path
  269. return get_lang_data(get_doc_path(module, doctype, name), None, 'doc')
  270. def get_lang_data(basepath, lang, mtype):
  271. """get language dict from langfile"""
  272. # add "locale" folder if reqd
  273. if os.path.basename(basepath) != 'locale':
  274. basepath = os.path.join(basepath, 'locale')
  275. if not lang: lang = webnotes.lang
  276. path = os.path.join(basepath, lang + '-' + mtype + '.json')
  277. langdata = {}
  278. if os.path.exists(path):
  279. with codecs.open(path, 'r', 'utf-8') as langfile:
  280. langdata = json.loads(langfile.read())
  281. return langdata
  282. def get_messages(basepath, mtype):
  283. """load list of messages from _message files"""
  284. # get message list
  285. path = os.path.join(basepath, '_messages_' + mtype + '.json')
  286. messages = []
  287. if os.path.exists(path):
  288. with open(path, 'r') as msgfile:
  289. messages = json.loads(msgfile.read())
  290. return messages
  291. def update_lang_js(jscode, path):
  292. return jscode + "\n\n$.extend(wn._messages, %s)" % \
  293. json.dumps(get_lang_data(path, webnotes.lang, 'js'))
  294. def get_all_messages_from_file(path):
  295. with codecs.open(path, 'r', 'utf-8') as msgfile:
  296. from csv import reader
  297. data = msgfile.read()
  298. data = reader([r.encode('utf-8') for r in data.splitlines()])
  299. newdata = []
  300. for row in data:
  301. newrow = []
  302. for val in row:
  303. newrow.append(unicode(val, 'utf-8'))
  304. newdata.append(newrow)
  305. return newdata
  306. def google_translate(lang, infile, outfile):
  307. """translate objects using Google API. Add you own API key for translation"""
  308. data = get_all_messages_from_file(infile)
  309. import requests
  310. with open(outfile, 'w') as msgfile:
  311. from csv import writer
  312. w = writer(msgfile)
  313. for row in data:
  314. if not row[1] and row[0] and row[0].strip():
  315. print 'translating: ' + row[0]
  316. response = requests.get("""https://www.googleapis.com/language/translate/v2""",
  317. params = {
  318. "key": conf.google_api_key,
  319. "source": "en",
  320. "target": lang,
  321. "q": row[0]
  322. })
  323. row[1] = response.json["data"]["translations"][0]["translatedText"]
  324. if not row[1]:
  325. row[1] = row[0] # google unable to translate!
  326. row[0] = row[0].encode('utf-8')
  327. row[1] = row[1].encode('utf-8')
  328. w.writerow(row)