update_currencies.py 5.0 KB

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