123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. # -*- coding: utf-8 -*-
  2. # This script generates languages.py from intersecting each engine's supported languages.
  3. #
  4. # Output files (engines_languages.json and languages.py)
  5. # are written in current directory to avoid overwriting in case something goes wrong.
  6. from json import dump
  7. import io
  8. from sys import path
  9. from babel import Locale, UnknownLocaleError
  10. from babel.languages import get_global
  11. path.append('../searx') # noqa
  12. from searx import settings
  13. from searx.engines import initialize_engines, engines
  14. # Output files.
  15. engines_languages_file = 'engines_languages.json'
  16. languages_file = 'languages.py'
  17. # Fetchs supported languages for each engine and writes json file with those.
  18. def fetch_supported_languages():
  19. engines_languages = {}
  20. for engine_name in engines:
  21. if hasattr(engines[engine_name], 'fetch_supported_languages'):
  22. try:
  23. engines_languages[engine_name] = engines[engine_name].fetch_supported_languages()
  24. except Exception as e:
  25. print(e)
  26. # write json file
  27. with io.open(engines_languages_file, "w", encoding="utf-8") as f:
  28. dump(engines_languages, f, ensure_ascii=False)
  29. return engines_languages
  30. # Get babel Locale object from lang_code if possible.
  31. def get_locale(lang_code):
  32. try:
  33. locale = Locale.parse(lang_code, sep='-')
  34. return locale
  35. except (UnknownLocaleError, ValueError):
  36. return None
  37. # Append engine_name to list of engines that support locale.
  38. def add_engine_counter(lang_code, engine_name, languages):
  39. if lang_code in languages:
  40. if 'counter' not in languages[lang_code]:
  41. languages[lang_code]['counter'] = [engine_name]
  42. elif engine_name not in languages[lang_code]['counter']:
  43. languages[lang_code]['counter'].append(engine_name)
  44. # Join all language lists.
  45. # TODO: Add language names from engine's language list if name not known by babel.
  46. def join_language_lists(engines_languages):
  47. language_list = {}
  48. for engine_name in engines_languages:
  49. for lang_code in engines_languages[engine_name]:
  50. # apply custom fixes if necessary
  51. if lang_code in getattr(engines[engine_name], 'language_aliases', {}).values():
  52. lang_code = next(lc for lc, alias in engines[engine_name].language_aliases.items()
  53. if lang_code == alias)
  54. locale = get_locale(lang_code)
  55. # ensure that lang_code uses standard language and country codes
  56. if locale and locale.territory:
  57. lang_code = locale.language + '-' + locale.territory
  58. # add locale if it's not in list
  59. if lang_code not in language_list:
  60. if locale:
  61. language_list[lang_code] = {'name': locale.get_language_name().title(),
  62. 'english_name': locale.english_name,
  63. 'country': locale.get_territory_name() or ''}
  64. # also add language without country
  65. if locale.language not in language_list:
  66. language_list[locale.language] = {'name': locale.get_language_name().title(),
  67. 'english_name': locale.english_name}
  68. else:
  69. language_list[lang_code] = {}
  70. # count engine for both language_country combination and language alone
  71. add_engine_counter(lang_code, engine_name, language_list)
  72. add_engine_counter(lang_code.split('-')[0], engine_name, language_list)
  73. return language_list
  74. # Filter language list so it only includes the most supported languages and countries.
  75. def filter_language_list(all_languages):
  76. min_supported_engines = 10
  77. main_engines = [engine_name for engine_name in engines.keys()
  78. if 'general' in engines[engine_name].categories and
  79. engines[engine_name].supported_languages and
  80. not engines[engine_name].disabled]
  81. # filter list to include only languages supported by most engines or all default general engines
  82. filtered_languages = {code: lang for code, lang
  83. in all_languages.items()
  84. if (len(lang.get('counter', [])) >= min_supported_engines or
  85. all(main_engine in lang.get('counter', [])
  86. for main_engine in main_engines))}
  87. return filtered_languages
  88. # Add country codes to languages without one and filter out language codes.
  89. def assign_country_codes(filtered_languages, all_languages):
  90. sorted_languages = sorted(all_languages,
  91. key=lambda lang: len(all_languages[lang].get('counter', [])),
  92. reverse=True)
  93. previous_lang = None
  94. previous_code = None
  95. countries = 0
  96. for current_code in sorted(filtered_languages):
  97. current_lang = current_code.split('-')[0]
  98. # count country codes per language
  99. if current_lang == previous_lang:
  100. countries += 1
  101. else:
  102. if previous_lang is not None:
  103. # if language has no single country code
  104. if countries == 0:
  105. # try to get country code with most supported engines
  106. for l in sorted_languages:
  107. l_parts = l.split('-')
  108. if len(l_parts) == 2 and l_parts[0] == previous_lang:
  109. filtered_languages[l] = all_languages[l]
  110. filtered_languages[l]['country'] = ''
  111. countries = 1
  112. break
  113. if countries == 0:
  114. # get most likely country code from babel
  115. subtags = get_global('likely_subtags').get(previous_lang)
  116. if subtags:
  117. subtag_parts = subtags.split('_')
  118. new_code = subtag_parts[0] + '-' + subtag_parts[-1]
  119. filtered_languages[new_code] = all_languages[previous_lang]
  120. countries = 1
  121. if countries == 1:
  122. # remove countryless version of language if there's only one country
  123. del filtered_languages[previous_lang]
  124. if previous_code in filtered_languages:
  125. filtered_languages[previous_code]['country'] = ''
  126. countries = 0
  127. previous_lang = current_lang
  128. previous_code = current_code
  129. # Write languages.py.
  130. def write_languages_file(languages):
  131. new_file = open(languages_file, 'wb')
  132. file_content = '# -*- coding: utf-8 -*-\n'\
  133. + '# list of language codes\n'\
  134. + '# this file is generated automatically by utils/update_search_languages.py\n'\
  135. + '\nlanguage_codes = ('
  136. for code in sorted(languages):
  137. file_content += '\n (u"' + code + '"'\
  138. + ', u"' + languages[code]['name'].split(' (')[0] + '"'\
  139. + ', u"' + languages[code].get('country', '') + '"'\
  140. + ', u"' + languages[code].get('english_name', '').split(' (')[0] + '"),'
  141. # remove last comma
  142. file_content = file_content[:-1]
  143. file_content += '\n)\n'
  144. new_file.write(file_content.encode('utf8'))
  145. new_file.close()
  146. if __name__ == "__main__":
  147. initialize_engines(settings['engines'])
  148. engines_languages = fetch_supported_languages()
  149. all_languages = join_language_lists(engines_languages)
  150. filtered_languages = filter_language_list(all_languages)
  151. assign_country_codes(filtered_languages, all_languages)
  152. write_languages_file(filtered_languages)