You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

341 rivejä
10 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 build_message_files():
  36. """build from doctypes, pages, database and framework"""
  37. build_for_pages('lib/core')
  38. build_for_pages('app')
  39. build_from_doctype_code('lib/core')
  40. build_from_doctype_code('app')
  41. # doctype
  42. build_from_database()
  43. build_for_framework('lib/webnotes', 'py', with_doctype_names=True)
  44. build_for_framework('lib/public/js/wn', 'js')
  45. build_for_framework('app/public/js', 'js', with_doctype_names=True)
  46. #build_for_modules()
  47. def build_for_pages(path):
  48. """make locale files for framework py and js (all)"""
  49. messages = []
  50. for (basepath, folders, files) in os.walk(path):
  51. if os.path.basename(os.path.dirname(basepath))=="page":
  52. messages_js, messages_py = [], []
  53. for fname in files:
  54. if fname.endswith('.js'):
  55. messages_js += get_message_list(os.path.join(basepath, fname))
  56. if fname.endswith('.py'):
  57. messages_py += get_message_list(os.path.join(basepath, fname))
  58. if messages_js:
  59. write_messages_file(basepath, messages_js, "js")
  60. if messages_py:
  61. write_messages_file(basepath, messages_py, "py")
  62. def build_for_modules():
  63. """doctype descriptions, module names, etc for each module"""
  64. from webnotes.modules import get_module_path, get_doc_path
  65. for m in webnotes.conn.sql("""select name from `tabModule Def`"""):
  66. module_path = get_module_path(m[0])
  67. if os.path.exists(module_path):
  68. messages = []
  69. messages += [t[0] for t in webnotes.conn.sql("""select description from tabDocType
  70. where module=%s""", m[0])]
  71. for t in webnotes.conn.sql("""select
  72. if(ifnull(title,'')='',name,title)
  73. from tabPage where module=%s
  74. and ifnull(standard,'No')='Yes' """, m[0]):
  75. messages.append(t[0])
  76. messages += [t[0] for t in webnotes.conn.sql("""select t1.name from
  77. tabReport t1, tabDocType t2 where
  78. t1.ref_doctype = t2.name and
  79. t1.is_standard = "Yes" and
  80. t2.module = %s""", m[0])]
  81. doctype_path = get_doc_path(m[0], 'Module Def', m[0])
  82. write_messages_file(doctype_path, messages, 'doc')
  83. def build_from_database():
  84. """make doctype labels, names, options, descriptions"""
  85. def get_select_options(doc):
  86. if doc.doctype=="DocField" and doc.fieldtype=='Select' and doc.options \
  87. and not doc.options.startswith("link:") \
  88. and not doc.options.startswith("attach_files:"):
  89. return doc.options.split('\n')
  90. else:
  91. return []
  92. build_for_doc_from_database(webnotes._dict({
  93. "doctype": "DocType",
  94. "module_field": "module",
  95. "DocType": ["name", "description", "module"],
  96. "DocField": ["label", "description"],
  97. "custom": get_select_options
  98. }))
  99. def build_for_doc_from_database(fields):
  100. from webnotes.modules import get_doc_path
  101. for item in webnotes.conn.sql("""select name from `tab%s`""" % fields.doctype, as_dict=1):
  102. messages = []
  103. doclist = webnotes.bean(fields.doctype, item.name).doclist
  104. for doc in doclist:
  105. if doc.doctype in fields:
  106. messages += map(lambda x: x in fields[doc.doctype] and doc.fields.get(x) or None,
  107. doc.fields.keys())
  108. if fields.custom:
  109. messages += fields.custom(doc)
  110. doc = doclist[0]
  111. if doc.fields.get(fields.module_field):
  112. doctype_path = get_doc_path(doc.fields[fields.module_field],
  113. doc.doctype, doc.name)
  114. write_messages_file(doctype_path, messages, 'doc')
  115. def build_for_framework(path, mtype, with_doctype_names = False):
  116. """make locale files for framework py and js (all)"""
  117. messages = []
  118. for (basepath, folders, files) in os.walk(path):
  119. for fname in files:
  120. if fname.endswith('.' + mtype):
  121. messages += get_message_list(os.path.join(basepath, fname))
  122. # append module & doctype names
  123. if with_doctype_names:
  124. for m in webnotes.conn.sql("""select name, module from `tabDocType`"""):
  125. messages.append(m[0])
  126. messages.append(m[1])
  127. if messages:
  128. write_messages_file(path, messages, mtype)
  129. def build_from_doctype_code(path):
  130. """walk and make locale files in all folders"""
  131. for (basepath, folders, files) in os.walk(path):
  132. messagespy = []
  133. messagesjs = []
  134. for fname in files:
  135. if fname.endswith('py'):
  136. messagespy += get_message_list(os.path.join(basepath, fname))
  137. if fname.endswith('js'):
  138. messagesjs += get_message_list(os.path.join(basepath, fname))
  139. if messagespy:
  140. write_messages_file(basepath, messagespy, 'py')
  141. if messagespy:
  142. write_messages_file(basepath, messagesjs, 'js')
  143. def get_message_list(path):
  144. """get list of messages from a code file"""
  145. import re
  146. messages = []
  147. with open(path, 'r') as sourcefile:
  148. txt = sourcefile.read()
  149. messages += re.findall('_\("([^"]*)"\)', txt)
  150. messages += re.findall("_\('([^']*)'\)", txt)
  151. messages += re.findall('_\("{3}([^"]*)"{3}\)', txt, re.S)
  152. return messages
  153. def write_messages_file(path, messages, mtype):
  154. """write messages to translation file"""
  155. if not os.path.exists(os.path.join(path, 'locale')):
  156. os.makedirs(os.path.join(path, 'locale'))
  157. fname = os.path.join(path, 'locale', '_messages_' + mtype + '.json')
  158. messages = list(set(messages))
  159. filtered = []
  160. for m in messages:
  161. if m and re.search('[a-zA-Z]+', m):
  162. filtered.append(m)
  163. with open(fname, 'w') as msgfile:
  164. msgfile.write(json.dumps(filtered, indent=1))
  165. def export_messages(lang, outfile):
  166. """get list of all messages"""
  167. messages = {}
  168. # extract messages
  169. for (basepath, folders, files) in os.walk('.'):
  170. def _get_messages(messages, basepath, mtype):
  171. mlist = get_messages(basepath, mtype)
  172. if not mlist:
  173. return
  174. # update messages with already existing translations
  175. langdata = get_lang_data(basepath, lang, mtype)
  176. for m in mlist:
  177. if not messages.get(m):
  178. messages[m] = langdata.get(m, "")
  179. if os.path.basename(basepath)=='locale':
  180. _get_messages(messages, basepath, 'doc')
  181. _get_messages(messages, basepath, 'py')
  182. _get_messages(messages, basepath, 'js')
  183. # remove duplicates
  184. if outfile:
  185. from csv import writer
  186. with open(outfile, 'w') as msgfile:
  187. w = writer(msgfile)
  188. keys = messages.keys()
  189. keys.sort()
  190. for m in keys:
  191. w.writerow([m.encode('utf-8'), messages.get(m, '').encode('utf-8')])
  192. def import_messages(lang, infile):
  193. """make individual message files for each language"""
  194. data = dict(get_all_messages_from_file(infile))
  195. for (basepath, folders, files) in os.walk('.'):
  196. def _update_lang_file(mtype):
  197. """create a langauge file for the given message type"""
  198. messages = get_messages(basepath, mtype)
  199. if not messages: return
  200. # read existing
  201. langdata = get_lang_data(basepath, lang, mtype)
  202. # update fresh
  203. for m in messages:
  204. if data.get(m):
  205. langdata[m] = data.get(m)
  206. if langdata:
  207. # write new langfile
  208. langfilename = os.path.join(basepath, lang + '-' + mtype + '.json')
  209. with open(langfilename, 'w') as langfile:
  210. langfile.write(json.dumps(langdata, indent=1, sort_keys=True).encode('utf-8'))
  211. #print 'wrote ' + langfilename
  212. if os.path.basename(basepath)=='locale':
  213. # make / update lang files for each type of message file (doc, js, py)
  214. # example: hi-doc.json, hi-js.json, hi-py.json
  215. _update_lang_file('doc')
  216. _update_lang_file('js')
  217. _update_lang_file('py')
  218. def get_doc_messages(module, doctype, name):
  219. from webnotes.modules import get_doc_path
  220. return get_lang_data(get_doc_path(module, doctype, name), None, 'doc')
  221. def get_lang_data(basepath, lang, mtype):
  222. """get language dict from langfile"""
  223. # add "locale" folder if reqd
  224. if os.path.basename(basepath) != 'locale':
  225. basepath = os.path.join(basepath, 'locale')
  226. if not lang: lang = webnotes.lang
  227. path = os.path.join(basepath, lang + '-' + mtype + '.json')
  228. langdata = {}
  229. if os.path.exists(path):
  230. with codecs.open(path, 'r', 'utf-8') as langfile:
  231. langdata = json.loads(langfile.read())
  232. return langdata
  233. def get_messages(basepath, mtype):
  234. """load list of messages from _message files"""
  235. # get message list
  236. path = os.path.join(basepath, '_messages_' + mtype + '.json')
  237. messages = []
  238. if os.path.exists(path):
  239. with open(path, 'r') as msgfile:
  240. messages = json.loads(msgfile.read())
  241. return messages
  242. def update_lang_js(jscode, path):
  243. return jscode + "\n\n$.extend(wn._messages, %s)" % \
  244. json.dumps(get_lang_data(path, webnotes.lang, 'js'))
  245. def get_all_messages_from_file(path):
  246. with codecs.open(path, 'r', 'utf-8') as msgfile:
  247. from csv import reader
  248. data = msgfile.read()
  249. data = reader([r.encode('utf-8') for r in data.splitlines()])
  250. newdata = []
  251. for row in data:
  252. newrow = []
  253. for val in row:
  254. newrow.append(unicode(val, 'utf-8'))
  255. newdata.append(newrow)
  256. return newdata
  257. def google_translate(lang, infile, outfile):
  258. """translate objects using Google API. Add you own API key for translation"""
  259. data = get_all_messages_from_file(infile)
  260. import requests
  261. with open(outfile, 'w') as msgfile:
  262. from csv import writer
  263. w = writer(msgfile)
  264. for row in data:
  265. if not row[1] and row[0] and row[0].strip():
  266. print 'translating: ' + row[0]
  267. response = requests.get("""https://www.googleapis.com/language/translate/v2""",
  268. params = {
  269. "key": conf.google_api_key,
  270. "source": "en",
  271. "target": lang,
  272. "q": row[0]
  273. })
  274. row[1] = response.json["data"]["translations"][0]["translatedText"]
  275. if not row[1]:
  276. row[1] = row[0] # google unable to translate!
  277. row[0] = row[0].encode('utf-8')
  278. row[1] = row[1].encode('utf-8')
  279. w.writerow(row)