update_wikidata_units.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. # * https://en.wikibooks.org/wiki/SPARQL/WIKIDATA_Precision,_Units_and_Coordinates#Quantities
  25. # see the result for https://www.wikidata.org/wiki/Q11582
  26. # there are multiple symbols the same rank
  27. SARQL_REQUEST = """
  28. SELECT DISTINCT ?item ?symbol ?tosi ?tosiUnit
  29. WHERE
  30. {
  31. ?item wdt:P31/wdt:P279 wd:Q47574 .
  32. ?item p:P5061 ?symbolP .
  33. ?symbolP ps:P5061 ?symbol ;
  34. wikibase:rank ?rank .
  35. OPTIONAL {
  36. ?item p:P2370 ?tosistmt .
  37. ?tosistmt psv:P2370 ?tosinode .
  38. ?tosinode wikibase:quantityAmount ?tosi .
  39. ?tosinode wikibase:quantityUnit ?tosiUnit .
  40. }
  41. FILTER(LANG(?symbol) = "en").
  42. }
  43. ORDER BY ?item DESC(?rank) ?symbol
  44. """
  45. def get_data():
  46. results = collections.OrderedDict()
  47. response = wikidata.send_wikidata_query(SARQL_REQUEST)
  48. for unit in response['results']['bindings']:
  49. symbol = unit['symbol']['value']
  50. name = unit['item']['value'].rsplit('/', 1)[1]
  51. si_name = unit.get('tosiUnit', {}).get('value', '')
  52. if si_name:
  53. si_name = si_name.rsplit('/', 1)[1]
  54. to_si_factor = unit.get('tosi', {}).get('value', '')
  55. if name not in results:
  56. # ignore duplicate: always use the first one
  57. results[name] = {
  58. 'symbol': symbol,
  59. 'si_name': si_name if si_name else None,
  60. 'to_si_factor': float(to_si_factor) if to_si_factor else None,
  61. }
  62. return results
  63. def get_wikidata_units_filename():
  64. return join(join(searx_dir, "data"), "")
  65. if __name__ == '__main__':
  66. with DATA_FILE.open('w', encoding="utf8") as f:
  67. json.dump(get_data(), f, indent=4, sort_keys=True, ensure_ascii=False)