update_currencies.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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. from searx.locales import LOCALE_NAMES, locales_initialize
  13. from searx.engines import wikidata, set_loggers
  14. from searx.data import data_dir
  15. DATA_FILE = data_dir / 'currencies.json'
  16. set_loggers(wikidata, 'wikidata')
  17. locales_initialize()
  18. # ORDER BY (with all the query fields) is important to keep a deterministic result order
  19. # so multiple invocation of this script doesn't change currencies.json
  20. SARQL_REQUEST = """
  21. SELECT DISTINCT ?iso4217 ?unit ?unicode ?label ?alias WHERE {
  22. ?item wdt:P498 ?iso4217; rdfs:label ?label.
  23. OPTIONAL { ?item skos:altLabel ?alias FILTER (LANG (?alias) = LANG(?label)). }
  24. OPTIONAL { ?item wdt:P5061 ?unit. }
  25. OPTIONAL { ?item wdt:P489 ?symbol.
  26. ?symbol wdt:P487 ?unicode. }
  27. MINUS { ?item wdt:P582 ?end_data . } # Ignore monney with an end date
  28. MINUS { ?item wdt:P31/wdt:P279* wd:Q15893266 . } # Ignore "former entity" (obsolete currency)
  29. FILTER(LANG(?label) IN (%LANGUAGES_SPARQL%)).
  30. }
  31. ORDER BY ?iso4217 ?unit ?unicode ?label ?alias
  32. """
  33. # ORDER BY (with all the query fields) is important to keep a deterministic result order
  34. # so multiple invocation of this script doesn't change currencies.json
  35. SPARQL_WIKIPEDIA_NAMES_REQUEST = """
  36. SELECT DISTINCT ?iso4217 ?article_name WHERE {
  37. ?item wdt:P498 ?iso4217 .
  38. ?article schema:about ?item ;
  39. schema:name ?article_name ;
  40. schema:isPartOf [ wikibase:wikiGroup "wikipedia" ]
  41. MINUS { ?item wdt:P582 ?end_data . } # Ignore monney with an end date
  42. MINUS { ?item wdt:P31/wdt:P279* wd:Q15893266 . } # Ignore "former entity" (obsolete currency)
  43. FILTER(LANG(?article_name) IN (%LANGUAGES_SPARQL%)).
  44. }
  45. ORDER BY ?iso4217 ?article_name
  46. """
  47. LANGUAGES = LOCALE_NAMES.keys()
  48. LANGUAGES_SPARQL = ', '.join(set(map(lambda l: repr(l.split('_')[0]), LANGUAGES)))
  49. def remove_accents(name):
  50. return unicodedata.normalize('NFKD', name).lower()
  51. def remove_extra(name):
  52. for c in ('(', ':'):
  53. if c in name:
  54. name = name.split(c)[0].strip()
  55. return name
  56. def _normalize_name(name):
  57. name = re.sub(' +', ' ', remove_accents(name.lower()).replace('-', ' '))
  58. name = remove_extra(name)
  59. return name
  60. def add_currency_name(db, name, iso4217, normalize_name=True):
  61. db_names = db['names']
  62. if normalize_name:
  63. name = _normalize_name(name)
  64. iso4217_set = db_names.setdefault(name, [])
  65. if iso4217 not in iso4217_set:
  66. iso4217_set.insert(0, iso4217)
  67. def add_currency_label(db, label, iso4217, language):
  68. labels = db['iso4217'].setdefault(iso4217, {})
  69. labels[language] = label
  70. def wikidata_request_result_iterator(request):
  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()