update_wikidata_units.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/env python
  2. # SPDX-License-Identifier: AGPL-3.0-or-later
  3. """Fetch units from :origin:`searx/engines/wikidata.py` engine.
  4. Output file: :origin:`searx/data/wikidata_units.json` (:origin:`CI Update data
  5. ... <.github/workflows/data-update.yml>`).
  6. """
  7. import json
  8. import collections
  9. # set path
  10. from os.path import join
  11. from searx import searx_dir
  12. from searx.engines import wikidata, set_loggers
  13. from searx.data import data_dir
  14. DATA_FILE = data_dir / 'wikidata_units.json'
  15. set_loggers(wikidata, 'wikidata')
  16. # the response contains duplicate ?item with the different ?symbol
  17. # "ORDER BY ?item DESC(?rank) ?symbol" provides a deterministic result
  18. # even if a ?item has different ?symbol of the same rank.
  19. # A deterministic result
  20. # see:
  21. # * https://www.wikidata.org/wiki/Help:Ranking
  22. # * https://www.mediawiki.org/wiki/Wikibase/Indexing/RDF_Dump_Format ("Statement representation" section)
  23. # * https://w.wiki/32BT
  24. # see the result for https://www.wikidata.org/wiki/Q11582
  25. # there are multiple symbols the same rank
  26. SARQL_REQUEST = """
  27. SELECT DISTINCT ?item ?symbol
  28. WHERE
  29. {
  30. ?item wdt:P31/wdt:P279 wd:Q47574 .
  31. ?item p:P5061 ?symbolP .
  32. ?symbolP ps:P5061 ?symbol ;
  33. wikibase:rank ?rank .
  34. FILTER(LANG(?symbol) = "en").
  35. }
  36. ORDER BY ?item DESC(?rank) ?symbol
  37. """
  38. def get_data():
  39. results = collections.OrderedDict()
  40. response = wikidata.send_wikidata_query(SARQL_REQUEST)
  41. for unit in response['results']['bindings']:
  42. name = unit['item']['value'].replace('http://www.wikidata.org/entity/', '')
  43. unit = unit['symbol']['value']
  44. if name not in results:
  45. # ignore duplicate: always use the first one
  46. results[name] = unit
  47. return results
  48. def get_wikidata_units_filename():
  49. return join(join(searx_dir, "data"), "")
  50. if __name__ == '__main__':
  51. with DATA_FILE.open('w', encoding="utf8") as f:
  52. json.dump(get_data(), f, indent=4, sort_keys=True, ensure_ascii=False)