fetch_languages.py 6.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. # -*- coding: utf-8 -*-
  2. # This script generates languages.py from intersecting each engine's supported languages.
  3. #
  4. # The country names are obtained from http://api.geonames.org which requires registering as a user.
  5. #
  6. # Output files (engines_languages.json and languages.py)
  7. # are written in current directory to avoid overwriting in case something goes wrong.
  8. from requests import get
  9. from urllib import urlencode
  10. from lxml.html import fromstring
  11. from json import loads, dumps
  12. import io
  13. from sys import path
  14. path.append('../searx') # noqa
  15. from searx.engines import engines
  16. # Geonames API for country names.
  17. geonames_user = '' # ADD USER NAME HERE
  18. country_names_url = 'http://api.geonames.org/countryInfoJSON?{parameters}'
  19. # Output files.
  20. engines_languages_file = 'engines_languages.json'
  21. languages_file = 'languages.py'
  22. engines_languages = {}
  23. # To filter out invalid codes and dialects.
  24. def valid_code(lang_code):
  25. # filter invalid codes
  26. # sl-SL is technically not invalid, but still a mistake
  27. invalid_codes = ['sl-SL', 'wt-WT', 'jw']
  28. invalid_countries = ['UK', 'XA', 'XL']
  29. if lang_code[:2] == 'xx'\
  30. or lang_code in invalid_codes\
  31. or lang_code[-2:] in invalid_countries\
  32. or is_dialect(lang_code):
  33. return False
  34. return True
  35. # Language codes with any additional tags other than language and country.
  36. def is_dialect(lang_code):
  37. lang_code = lang_code.split('-')
  38. if len(lang_code) > 2 or len(lang_code[0]) > 3:
  39. return True
  40. if len(lang_code) == 2 and len(lang_code[1]) > 2:
  41. return True
  42. return False
  43. # Get country name in specified language.
  44. def get_country_name(locale):
  45. if geonames_user is '':
  46. return ''
  47. locale = locale.split('-')
  48. if len(locale) != 2:
  49. return ''
  50. url = country_names_url.format(parameters=urlencode({'lang': locale[0],
  51. 'country': locale[1],
  52. 'username': geonames_user}))
  53. response = get(url)
  54. json = loads(response.text)
  55. content = json.get('geonames', None)
  56. if content is None or len(content) != 1:
  57. print "No country name found for " + locale[0] + "-" + locale[1]
  58. return ''
  59. return content[0].get('countryName', '')
  60. # Fetchs supported languages for each engine and writes json file with those.
  61. def fetch_supported_languages():
  62. for engine_name in engines:
  63. if hasattr(engines[engine_name], 'fetch_supported_languages'):
  64. try:
  65. engines_languages[engine_name] = engines[engine_name].fetch_supported_languages()
  66. except Exception as e:
  67. print e
  68. # write json file
  69. with io.open(engines_languages_file, "w", encoding="utf-8") as f:
  70. f.write(unicode(dumps(engines_languages, ensure_ascii=False, encoding="utf-8")))
  71. # Join all language lists.
  72. # Iterate all languages supported by each engine.
  73. def join_language_lists():
  74. global languages
  75. # include wikipedia first for more accurate language names
  76. languages = {code: lang for code, lang
  77. in engines_languages['wikipedia'].iteritems()
  78. if valid_code(code)}
  79. for engine_name in engines_languages:
  80. for locale in engines_languages[engine_name]:
  81. if valid_code(locale):
  82. # if language is not on list or if it has no name yet
  83. if locale not in languages or not languages[locale].get('name'):
  84. if isinstance(engines_languages[engine_name], dict):
  85. languages[locale] = engines_languages[engine_name][locale]
  86. else:
  87. languages[locale] = {}
  88. # add to counter of engines that support given language
  89. lang = locale.split('-')[0]
  90. if lang in languages:
  91. if 'counter' not in languages[lang]:
  92. languages[lang]['counter'] = [engine_name]
  93. elif engine_name not in languages[lang]['counter']:
  94. languages[lang]['counter'].append(engine_name)
  95. # filter list to include only languages supported by most engines
  96. min_supported_engines = int(0.75 * len(engines_languages))
  97. languages = {code: lang for code, lang
  98. in languages.iteritems()
  99. if len(lang.get('counter', [])) >= min_supported_engines or
  100. len(languages.get(code.split('-')[0], {}).get('counter', [])) >= min_supported_engines}
  101. # get locales that have no name or country yet
  102. for locale in languages.keys():
  103. # try to get language names
  104. if not languages[locale].get('name'):
  105. name = languages.get(locale.split('-')[0], {}).get('name', None)
  106. if name:
  107. languages[locale]['name'] = name
  108. else:
  109. # filter out locales with no name
  110. del languages[locale]
  111. continue
  112. # try to get language name in english
  113. if not languages[locale].get('english_name'):
  114. languages[locale]['english_name'] = languages.get(locale.split('-')[0], {}).get('english_name', '')
  115. # try to get country name
  116. if locale.find('-') > 0 and not languages[locale].get('country'):
  117. languages[locale]['country'] = get_country_name(locale) or ''
  118. # Remove countryless language if language is featured in only one country.
  119. def filter_single_country_languages():
  120. prev_lang = None
  121. prev_code = None
  122. for code in sorted(languages):
  123. lang = code.split('-')[0]
  124. if lang == prev_lang:
  125. countries += 1
  126. else:
  127. if prev_lang is not None and countries == 1:
  128. del languages[prev_lang]
  129. languages[prev_code]['country'] = ''
  130. countries = 0
  131. prev_lang = lang
  132. prev_code = code
  133. # Write languages.py.
  134. def write_languages_file():
  135. new_file = open(languages_file, 'w')
  136. file_content = '# -*- coding: utf-8 -*-\n'\
  137. + '# list of language codes\n'\
  138. + '# this file is generated automatically by utils/update_search_languages.py\n'\
  139. + '\nlanguage_codes = ('
  140. for code in sorted(languages):
  141. file_content += '\n (u"' + code + '"'\
  142. + ', u"' + languages[code]['name'].split(' (')[0] + '"'\
  143. + ', u"' + languages[code].get('country', '') + '"'\
  144. + ', u"' + languages[code].get('english_name', '').split(' (')[0] + '"),'
  145. # remove last comma
  146. file_content = file_content[:-1]
  147. file_content += '\n)\n'
  148. new_file.write(file_content.encode('utf8'))
  149. new_file.close()
  150. if __name__ == "__main__":
  151. fetch_supported_languages()
  152. join_language_lists()
  153. filter_single_country_languages()
  154. write_languages_file()