update_currencies.py 4.7 KB

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