update_currencies.py 4.7 KB

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