update_currencies.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. #!/usr/bin/env python
  2. import re
  3. import unicodedata
  4. import json
  5. # set path
  6. from sys import path
  7. from os.path import realpath, dirname, join
  8. from searx import searx_dir
  9. from searx.locales import LOCALE_NAMES
  10. from searx.engines.wikidata import send_wikidata_query
  11. # ORDER BY (with all the query fields) is important to keep a deterministic result order
  12. # so multiple invokation of this script doesn't change currencies.json
  13. SARQL_REQUEST = """
  14. SELECT DISTINCT ?iso4217 ?unit ?unicode ?label ?alias WHERE {
  15. ?item wdt:P498 ?iso4217; rdfs:label ?label.
  16. OPTIONAL { ?item skos:altLabel ?alias FILTER (LANG (?alias) = LANG(?label)). }
  17. OPTIONAL { ?item wdt:P5061 ?unit. }
  18. OPTIONAL { ?item wdt:P489 ?symbol.
  19. ?symbol wdt:P487 ?unicode. }
  20. MINUS { ?item wdt:P582 ?end_data . } # Ignore monney with an end date
  21. MINUS { ?item wdt:P31/wdt:P279* wd:Q15893266 . } # Ignore "former entity" (obsolete currency)
  22. FILTER(LANG(?label) IN (%LANGUAGES_SPARQL%)).
  23. }
  24. ORDER BY ?iso4217 ?unit ?unicode ?label ?alias
  25. """
  26. # ORDER BY (with all the query fields) is important to keep a deterministic result order
  27. # so multiple invokation of this script doesn't change currencies.json
  28. SPARQL_WIKIPEDIA_NAMES_REQUEST = """
  29. SELECT DISTINCT ?iso4217 ?article_name WHERE {
  30. ?item wdt:P498 ?iso4217 .
  31. ?article schema:about ?item ;
  32. schema:name ?article_name ;
  33. schema:isPartOf [ wikibase:wikiGroup "wikipedia" ]
  34. MINUS { ?item wdt:P582 ?end_data . } # Ignore monney with an end date
  35. MINUS { ?item wdt:P31/wdt:P279* wd:Q15893266 . } # Ignore "former entity" (obsolete currency)
  36. FILTER(LANG(?article_name) IN (%LANGUAGES_SPARQL%)).
  37. }
  38. ORDER BY ?iso4217 ?article_name
  39. """
  40. LANGUAGES = LOCALE_NAMES.keys()
  41. LANGUAGES_SPARQL = ', '.join(set(map(lambda l: repr(l.split('_')[0]), LANGUAGES)))
  42. def remove_accents(name):
  43. return unicodedata.normalize('NFKD', name).lower()
  44. def remove_extra(name):
  45. for c in ('(', ':'):
  46. if c in name:
  47. name = name.split(c)[0].strip()
  48. return name
  49. def _normalize_name(name):
  50. name = re.sub(' +', ' ', remove_accents(name.lower()).replace('-', ' '))
  51. name = remove_extra(name)
  52. return name
  53. def add_currency_name(db, name, iso4217, normalize_name=True):
  54. db_names = db['names']
  55. if normalize_name:
  56. name = _normalize_name(name)
  57. iso4217_set = db_names.setdefault(name, [])
  58. if iso4217 not in iso4217_set:
  59. iso4217_set.insert(0, iso4217)
  60. def add_currency_label(db, label, iso4217, language):
  61. labels = db['iso4217'].setdefault(iso4217, {})
  62. labels[language] = label
  63. def wikidata_request_result_iterator(request):
  64. result = send_wikidata_query(request.replace('%LANGUAGES_SPARQL%', LANGUAGES_SPARQL))
  65. if result is not None:
  66. for r in result['results']['bindings']:
  67. yield r
  68. def fetch_db():
  69. db = {
  70. 'names': {},
  71. 'iso4217': {},
  72. }
  73. for r in wikidata_request_result_iterator(SPARQL_WIKIPEDIA_NAMES_REQUEST):
  74. iso4217 = r['iso4217']['value']
  75. article_name = r['article_name']['value']
  76. article_lang = r['article_name']['xml:lang']
  77. add_currency_name(db, article_name, iso4217)
  78. add_currency_label(db, article_name, iso4217, article_lang)
  79. for r in wikidata_request_result_iterator(SARQL_REQUEST):
  80. iso4217 = r['iso4217']['value']
  81. if 'label' in r:
  82. label = r['label']['value']
  83. label_lang = r['label']['xml:lang']
  84. add_currency_name(db, label, iso4217)
  85. add_currency_label(db, label, iso4217, label_lang)
  86. if 'alias' in r:
  87. add_currency_name(db, r['alias']['value'], iso4217)
  88. if 'unicode' in r:
  89. add_currency_name(db, r['unicode']['value'], iso4217, normalize_name=False)
  90. if 'unit' in r:
  91. add_currency_name(db, r['unit']['value'], iso4217, normalize_name=False)
  92. # reduce memory usage:
  93. # replace lists with one item by the item.
  94. # see searx.search.processors.online_currency.name_to_iso4217
  95. for name in db['names']:
  96. if len(db['names'][name]) == 1:
  97. db['names'][name] = db['names'][name][0]
  98. return db
  99. def get_filename():
  100. return join(join(searx_dir, "data"), "currencies.json")
  101. def main():
  102. #
  103. db = fetch_db()
  104. # static
  105. add_currency_name(db, "euro", 'EUR')
  106. add_currency_name(db, "euros", 'EUR')
  107. add_currency_name(db, "dollar", 'USD')
  108. add_currency_name(db, "dollars", 'USD')
  109. add_currency_name(db, "peso", 'MXN')
  110. add_currency_name(db, "pesos", 'MXN')
  111. with open(get_filename(), 'w', encoding='utf8') as f:
  112. json.dump(db, f, ensure_ascii=False, indent=4)
  113. if __name__ == '__main__':
  114. main()