update_currencies.py 4.9 KB

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