wikidata.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """
  3. Wikidata
  4. """
  5. from urllib.parse import urlencode
  6. from json import loads
  7. from dateutil.parser import isoparse
  8. from babel.dates import format_datetime, format_date, format_time, get_datetime_format
  9. from searx.data import WIKIDATA_UNITS
  10. from searx.network import post, get
  11. from searx.utils import match_language, searx_useragent, get_string_replaces_function
  12. from searx.external_urls import get_external_url, get_earth_coordinates_url, area_to_osm_zoom
  13. from searx.engines.wikipedia import _fetch_supported_languages, supported_languages_url # NOQA # pylint: disable=unused-import
  14. # about
  15. about = {
  16. "website": 'https://wikidata.org/',
  17. "wikidata_id": 'Q2013',
  18. "official_api_documentation": 'https://query.wikidata.org/',
  19. "use_official_api": True,
  20. "require_api_key": False,
  21. "results": 'JSON',
  22. }
  23. # SPARQL
  24. SPARQL_ENDPOINT_URL = 'https://query.wikidata.org/sparql'
  25. SPARQL_EXPLAIN_URL = 'https://query.wikidata.org/bigdata/namespace/wdq/sparql?explain'
  26. WIKIDATA_PROPERTIES = {
  27. 'P434': 'MusicBrainz',
  28. 'P435': 'MusicBrainz',
  29. 'P436': 'MusicBrainz',
  30. 'P966': 'MusicBrainz',
  31. 'P345': 'IMDb',
  32. 'P2397': 'YouTube',
  33. 'P1651': 'YouTube',
  34. 'P2002': 'Twitter',
  35. 'P2013': 'Facebook',
  36. 'P2003': 'Instagram',
  37. }
  38. # SERVICE wikibase:mwapi : https://www.mediawiki.org/wiki/Wikidata_Query_Service/User_Manual/MWAPI
  39. # SERVICE wikibase:label: https://en.wikibooks.org/wiki/SPARQL/SERVICE_-_Label#Manual_Label_SERVICE
  40. # https://en.wikibooks.org/wiki/SPARQL/WIKIDATA_Precision,_Units_and_Coordinates
  41. # https://www.mediawiki.org/wiki/Wikibase/Indexing/RDF_Dump_Format#Data_model
  42. # optmization:
  43. # * https://www.wikidata.org/wiki/Wikidata:SPARQL_query_service/query_optimization
  44. # * https://github.com/blazegraph/database/wiki/QueryHints
  45. QUERY_TEMPLATE = """
  46. SELECT ?item ?itemLabel ?itemDescription ?lat ?long %SELECT%
  47. WHERE
  48. {
  49. SERVICE wikibase:mwapi {
  50. bd:serviceParam wikibase:endpoint "www.wikidata.org";
  51. wikibase:api "EntitySearch";
  52. wikibase:limit 1;
  53. mwapi:search "%QUERY%";
  54. mwapi:language "%LANGUAGE%".
  55. ?item wikibase:apiOutputItem mwapi:item.
  56. }
  57. %WHERE%
  58. SERVICE wikibase:label {
  59. bd:serviceParam wikibase:language "%LANGUAGE%,en".
  60. ?item rdfs:label ?itemLabel .
  61. ?item schema:description ?itemDescription .
  62. %WIKIBASE_LABELS%
  63. }
  64. }
  65. GROUP BY ?item ?itemLabel ?itemDescription ?lat ?long %GROUP_BY%
  66. """
  67. # Get the calendar names and the property names
  68. QUERY_PROPERTY_NAMES = """
  69. SELECT ?item ?name
  70. WHERE {
  71. {
  72. SELECT ?item
  73. WHERE { ?item wdt:P279* wd:Q12132 }
  74. } UNION {
  75. VALUES ?item { %ATTRIBUTES% }
  76. }
  77. OPTIONAL { ?item rdfs:label ?name. }
  78. }
  79. """
  80. # https://www.w3.org/TR/sparql11-query/#rSTRING_LITERAL1
  81. # https://lists.w3.org/Archives/Public/public-rdf-dawg/2011OctDec/0175.html
  82. sparql_string_escape = get_string_replaces_function({'\t': '\\\t',
  83. '\n': '\\\n',
  84. '\r': '\\\r',
  85. '\b': '\\\b',
  86. '\f': '\\\f',
  87. '\"': '\\\"',
  88. '\'': '\\\'',
  89. '\\': '\\\\'})
  90. replace_http_by_https = get_string_replaces_function({'http:': 'https:'})
  91. def get_headers():
  92. # user agent: https://www.mediawiki.org/wiki/Wikidata_Query_Service/User_Manual#Query_limits
  93. return {
  94. 'Accept': 'application/sparql-results+json',
  95. 'User-Agent': searx_useragent()
  96. }
  97. def get_label_for_entity(entity_id, language):
  98. name = WIKIDATA_PROPERTIES.get(entity_id)
  99. if name is None:
  100. name = WIKIDATA_PROPERTIES.get((entity_id, language))
  101. if name is None:
  102. name = WIKIDATA_PROPERTIES.get((entity_id, language.split('-')[0]))
  103. if name is None:
  104. name = WIKIDATA_PROPERTIES.get((entity_id, 'en'))
  105. if name is None:
  106. name = entity_id
  107. return name
  108. def send_wikidata_query(query, method='GET'):
  109. if method == 'GET':
  110. # query will be cached by wikidata
  111. http_response = get(SPARQL_ENDPOINT_URL + '?' + urlencode({'query': query}), headers=get_headers())
  112. else:
  113. # query won't be cached by wikidata
  114. http_response = post(SPARQL_ENDPOINT_URL, data={'query': query}, headers=get_headers())
  115. if http_response.status_code != 200:
  116. logger.debug('SPARQL endpoint error %s', http_response.content.decode())
  117. logger.debug('request time %s', str(http_response.elapsed))
  118. http_response.raise_for_status()
  119. return loads(http_response.content.decode())
  120. def request(query, params):
  121. language = params['language'].split('-')[0]
  122. if language == 'all':
  123. language = 'en'
  124. else:
  125. language = match_language(params['language'], supported_languages, language_aliases).split('-')[0]
  126. query, attributes = get_query(query, language)
  127. params['method'] = 'POST'
  128. params['url'] = SPARQL_ENDPOINT_URL
  129. params['data'] = {'query': query}
  130. params['headers'] = get_headers()
  131. params['language'] = language
  132. params['attributes'] = attributes
  133. return params
  134. def response(resp):
  135. results = []
  136. jsonresponse = loads(resp.content.decode())
  137. language = resp.search_params['language'].lower()
  138. attributes = resp.search_params['attributes']
  139. seen_entities = set()
  140. for result in jsonresponse.get('results', {}).get('bindings', []):
  141. attribute_result = {key: value['value'] for key, value in result.items()}
  142. entity_url = attribute_result['item']
  143. if entity_url not in seen_entities:
  144. seen_entities.add(entity_url)
  145. results += get_results(attribute_result, attributes, language)
  146. else:
  147. logger.debug('The SPARQL request returns duplicate entities: %s', str(attribute_result))
  148. return results
  149. def get_results(attribute_result, attributes, language):
  150. results = []
  151. infobox_title = attribute_result.get('itemLabel')
  152. infobox_id = attribute_result['item']
  153. infobox_id_lang = None
  154. infobox_urls = []
  155. infobox_attributes = []
  156. infobox_content = attribute_result.get('itemDescription', [])
  157. img_src = None
  158. img_src_priority = 100
  159. for attribute in attributes:
  160. value = attribute.get_str(attribute_result, language)
  161. if value is not None and value != '':
  162. attribute_type = type(attribute)
  163. if attribute_type in (WDURLAttribute, WDArticle):
  164. # get_select() method : there is group_concat(distinct ...;separator=", ")
  165. # split the value here
  166. for url in value.split(', '):
  167. infobox_urls.append({'title': attribute.get_label(language), 'url': url, **attribute.kwargs})
  168. # "normal" results (not infobox) include official website and Wikipedia links.
  169. if attribute.kwargs.get('official') or attribute_type == WDArticle:
  170. results.append({'title': infobox_title, 'url': url})
  171. # update the infobox_id with the wikipedia URL
  172. # first the local wikipedia URL, and as fallback the english wikipedia URL
  173. if attribute_type == WDArticle\
  174. and ((attribute.language == 'en' and infobox_id_lang is None)
  175. or attribute.language != 'en'):
  176. infobox_id_lang = attribute.language
  177. infobox_id = url
  178. elif attribute_type == WDImageAttribute:
  179. # this attribute is an image.
  180. # replace the current image only the priority is lower
  181. # (the infobox contain only one image).
  182. if attribute.priority < img_src_priority:
  183. img_src = value
  184. img_src_priority = attribute.priority
  185. elif attribute_type == WDGeoAttribute:
  186. # geocoordinate link
  187. # use the area to get the OSM zoom
  188. # Note: ignre the unit (must be km² otherwise the calculation is wrong)
  189. # Should use normalized value p:P2046/psn:P2046/wikibase:quantityAmount
  190. area = attribute_result.get('P2046')
  191. osm_zoom = area_to_osm_zoom(area) if area else 19
  192. url = attribute.get_geo_url(attribute_result, osm_zoom=osm_zoom)
  193. if url:
  194. infobox_urls.append({'title': attribute.get_label(language),
  195. 'url': url,
  196. 'entity': attribute.name})
  197. else:
  198. infobox_attributes.append({'label': attribute.get_label(language),
  199. 'value': value,
  200. 'entity': attribute.name})
  201. if infobox_id:
  202. infobox_id = replace_http_by_https(infobox_id)
  203. # add the wikidata URL at the end
  204. infobox_urls.append({'title': 'Wikidata', 'url': attribute_result['item']})
  205. if img_src is None and len(infobox_attributes) == 0 and len(infobox_urls) == 1 and\
  206. len(infobox_content) == 0:
  207. results.append({
  208. 'url': infobox_urls[0]['url'],
  209. 'title': infobox_title,
  210. 'content': infobox_content
  211. })
  212. else:
  213. results.append({
  214. 'infobox': infobox_title,
  215. 'id': infobox_id,
  216. 'content': infobox_content,
  217. 'img_src': img_src,
  218. 'urls': infobox_urls,
  219. 'attributes': infobox_attributes
  220. })
  221. return results
  222. def get_query(query, language):
  223. attributes = get_attributes(language)
  224. select = [a.get_select() for a in attributes]
  225. where = list(filter(lambda s: len(s) > 0, [a.get_where() for a in attributes]))
  226. wikibase_label = list(filter(lambda s: len(s) > 0, [a.get_wikibase_label() for a in attributes]))
  227. group_by = list(filter(lambda s: len(s) > 0, [a.get_group_by() for a in attributes]))
  228. query = QUERY_TEMPLATE\
  229. .replace('%QUERY%', sparql_string_escape(query))\
  230. .replace('%SELECT%', ' '.join(select))\
  231. .replace('%WHERE%', '\n '.join(where))\
  232. .replace('%WIKIBASE_LABELS%', '\n '.join(wikibase_label))\
  233. .replace('%GROUP_BY%', ' '.join(group_by))\
  234. .replace('%LANGUAGE%', language)
  235. return query, attributes
  236. def get_attributes(language):
  237. attributes = []
  238. def add_value(name):
  239. attributes.append(WDAttribute(name))
  240. def add_amount(name):
  241. attributes.append(WDAmountAttribute(name))
  242. def add_label(name):
  243. attributes.append(WDLabelAttribute(name))
  244. def add_url(name, url_id=None, **kwargs):
  245. attributes.append(WDURLAttribute(name, url_id, kwargs))
  246. def add_image(name, url_id=None, priority=1):
  247. attributes.append(WDImageAttribute(name, url_id, priority))
  248. def add_date(name):
  249. attributes.append(WDDateAttribute(name))
  250. # Dates
  251. for p in ['P571', # inception date
  252. 'P576', # dissolution date
  253. 'P580', # start date
  254. 'P582', # end date
  255. 'P569', # date of birth
  256. 'P570', # date of death
  257. 'P619', # date of spacecraft launch
  258. 'P620']: # date of spacecraft landing
  259. add_date(p)
  260. for p in ['P27', # country of citizenship
  261. 'P495', # country of origin
  262. 'P17', # country
  263. 'P159']: # headquarters location
  264. add_label(p)
  265. # Places
  266. for p in ['P36', # capital
  267. 'P35', # head of state
  268. 'P6', # head of government
  269. 'P122', # basic form of government
  270. 'P37']: # official language
  271. add_label(p)
  272. add_value('P1082') # population
  273. add_amount('P2046') # area
  274. add_amount('P281') # postal code
  275. add_label('P38') # currency
  276. add_amount('P2048') # heigth (building)
  277. # Media
  278. for p in ['P400', # platform (videogames, computing)
  279. 'P50', # author
  280. 'P170', # creator
  281. 'P57', # director
  282. 'P175', # performer
  283. 'P178', # developer
  284. 'P162', # producer
  285. 'P176', # manufacturer
  286. 'P58', # screenwriter
  287. 'P272', # production company
  288. 'P264', # record label
  289. 'P123', # publisher
  290. 'P449', # original network
  291. 'P750', # distributed by
  292. 'P86']: # composer
  293. add_label(p)
  294. add_date('P577') # publication date
  295. add_label('P136') # genre (music, film, artistic...)
  296. add_label('P364') # original language
  297. add_value('P212') # ISBN-13
  298. add_value('P957') # ISBN-10
  299. add_label('P275') # copyright license
  300. add_label('P277') # programming language
  301. add_value('P348') # version
  302. add_label('P840') # narrative location
  303. # Languages
  304. add_value('P1098') # number of speakers
  305. add_label('P282') # writing system
  306. add_label('P1018') # language regulatory body
  307. add_value('P218') # language code (ISO 639-1)
  308. # Other
  309. add_label('P169') # ceo
  310. add_label('P112') # founded by
  311. add_label('P1454') # legal form (company, organization)
  312. add_label('P137') # operator (service, facility, ...)
  313. add_label('P1029') # crew members (tripulation)
  314. add_label('P225') # taxon name
  315. add_value('P274') # chemical formula
  316. add_label('P1346') # winner (sports, contests, ...)
  317. add_value('P1120') # number of deaths
  318. add_value('P498') # currency code (ISO 4217)
  319. # URL
  320. add_url('P856', official=True) # official website
  321. attributes.append(WDArticle(language)) # wikipedia (user language)
  322. if not language.startswith('en'):
  323. attributes.append(WDArticle('en')) # wikipedia (english)
  324. add_url('P1324') # source code repository
  325. add_url('P1581') # blog
  326. add_url('P434', url_id='musicbrainz_artist')
  327. add_url('P435', url_id='musicbrainz_work')
  328. add_url('P436', url_id='musicbrainz_release_group')
  329. add_url('P966', url_id='musicbrainz_label')
  330. add_url('P345', url_id='imdb_id')
  331. add_url('P2397', url_id='youtube_channel')
  332. add_url('P1651', url_id='youtube_video')
  333. add_url('P2002', url_id='twitter_profile')
  334. add_url('P2013', url_id='facebook_profile')
  335. add_url('P2003', url_id='instagram_profile')
  336. # Map
  337. attributes.append(WDGeoAttribute('P625'))
  338. # Image
  339. add_image('P15', priority=1, url_id='wikimedia_image') # route map
  340. add_image('P242', priority=2, url_id='wikimedia_image') # locator map
  341. add_image('P154', priority=3, url_id='wikimedia_image') # logo
  342. add_image('P18', priority=4, url_id='wikimedia_image') # image
  343. add_image('P41', priority=5, url_id='wikimedia_image') # flag
  344. add_image('P2716', priority=6, url_id='wikimedia_image') # collage
  345. add_image('P2910', priority=7, url_id='wikimedia_image') # icon
  346. return attributes
  347. class WDAttribute:
  348. __slots__ = 'name',
  349. def __init__(self, name):
  350. self.name = name
  351. def get_select(self):
  352. return '(group_concat(distinct ?{name};separator=", ") as ?{name}s)'.replace('{name}', self.name)
  353. def get_label(self, language):
  354. return get_label_for_entity(self.name, language)
  355. def get_where(self):
  356. return "OPTIONAL { ?item wdt:{name} ?{name} . }".replace('{name}', self.name)
  357. def get_wikibase_label(self):
  358. return ""
  359. def get_group_by(self):
  360. return ""
  361. def get_str(self, result, language):
  362. return result.get(self.name + 's')
  363. def __repr__(self):
  364. return '<' + str(type(self).__name__) + ':' + self.name + '>'
  365. class WDAmountAttribute(WDAttribute):
  366. def get_select(self):
  367. return '?{name} ?{name}Unit'.replace('{name}', self.name)
  368. def get_where(self):
  369. return """ OPTIONAL { ?item p:{name} ?{name}Node .
  370. ?{name}Node rdf:type wikibase:BestRank ; ps:{name} ?{name} .
  371. OPTIONAL { ?{name}Node psv:{name}/wikibase:quantityUnit ?{name}Unit. } }""".replace('{name}', self.name)
  372. def get_group_by(self):
  373. return self.get_select()
  374. def get_str(self, result, language):
  375. value = result.get(self.name)
  376. unit = result.get(self.name + "Unit")
  377. if unit is not None:
  378. unit = unit.replace('http://www.wikidata.org/entity/', '')
  379. return value + " " + get_label_for_entity(unit, language)
  380. return value
  381. class WDArticle(WDAttribute):
  382. __slots__ = 'language', 'kwargs'
  383. def __init__(self, language, kwargs=None):
  384. super().__init__('wikipedia')
  385. self.language = language
  386. self.kwargs = kwargs or {}
  387. def get_label(self, language):
  388. # language parameter is ignored
  389. return "Wikipedia ({language})".replace('{language}', self.language)
  390. def get_select(self):
  391. return "?article{language} ?articleName{language}".replace('{language}', self.language)
  392. def get_where(self):
  393. return """OPTIONAL { ?article{language} schema:about ?item ;
  394. schema:inLanguage "{language}" ;
  395. schema:isPartOf <https://{language}.wikipedia.org/> ;
  396. schema:name ?articleName{language} . }""".replace('{language}', self.language)
  397. def get_group_by(self):
  398. return self.get_select()
  399. def get_str(self, result, language):
  400. key = 'article{language}'.replace('{language}', self.language)
  401. return result.get(key)
  402. class WDLabelAttribute(WDAttribute):
  403. def get_select(self):
  404. return '(group_concat(distinct ?{name}Label;separator=", ") as ?{name}Labels)'.replace('{name}', self.name)
  405. def get_where(self):
  406. return "OPTIONAL { ?item wdt:{name} ?{name} . }".replace('{name}', self.name)
  407. def get_wikibase_label(self):
  408. return "?{name} rdfs:label ?{name}Label .".replace('{name}', self.name)
  409. def get_str(self, result, language):
  410. return result.get(self.name + 'Labels')
  411. class WDURLAttribute(WDAttribute):
  412. HTTP_WIKIMEDIA_IMAGE = 'http://commons.wikimedia.org/wiki/Special:FilePath/'
  413. __slots__ = 'url_id', 'kwargs'
  414. def __init__(self, name, url_id=None, kwargs=None):
  415. super().__init__(name)
  416. self.url_id = url_id
  417. self.kwargs = kwargs
  418. def get_str(self, result, language):
  419. value = result.get(self.name + 's')
  420. if self.url_id and value is not None and value != '':
  421. value = value.split(',')[0]
  422. url_id = self.url_id
  423. if value.startswith(WDURLAttribute.HTTP_WIKIMEDIA_IMAGE):
  424. value = value[len(WDURLAttribute.HTTP_WIKIMEDIA_IMAGE):]
  425. url_id = 'wikimedia_image'
  426. return get_external_url(url_id, value)
  427. return value
  428. class WDGeoAttribute(WDAttribute):
  429. def get_label(self, language):
  430. return "OpenStreetMap"
  431. def get_select(self):
  432. return "?{name}Lat ?{name}Long".replace('{name}', self.name)
  433. def get_where(self):
  434. return """OPTIONAL { ?item p:{name}/psv:{name} [
  435. wikibase:geoLatitude ?{name}Lat ;
  436. wikibase:geoLongitude ?{name}Long ] }""".replace('{name}', self.name)
  437. def get_group_by(self):
  438. return self.get_select()
  439. def get_str(self, result, language):
  440. latitude = result.get(self.name + 'Lat')
  441. longitude = result.get(self.name + 'Long')
  442. if latitude and longitude:
  443. return latitude + ' ' + longitude
  444. return None
  445. def get_geo_url(self, result, osm_zoom=19):
  446. latitude = result.get(self.name + 'Lat')
  447. longitude = result.get(self.name + 'Long')
  448. if latitude and longitude:
  449. return get_earth_coordinates_url(latitude, longitude, osm_zoom)
  450. return None
  451. class WDImageAttribute(WDURLAttribute):
  452. __slots__ = 'priority',
  453. def __init__(self, name, url_id=None, priority=100):
  454. super().__init__(name, url_id)
  455. self.priority = priority
  456. class WDDateAttribute(WDAttribute):
  457. def get_select(self):
  458. return '?{name} ?{name}timePrecision ?{name}timeZone ?{name}timeCalendar'.replace('{name}', self.name)
  459. def get_where(self):
  460. # To remove duplicate, add
  461. # FILTER NOT EXISTS { ?item p:{name}/psv:{name}/wikibase:timeValue ?{name}bis FILTER (?{name}bis < ?{name}) }
  462. # this filter is too slow, so the response function ignore duplicate results
  463. # (see the seen_entities variable)
  464. return """OPTIONAL { ?item p:{name}/psv:{name} [
  465. wikibase:timeValue ?{name} ;
  466. wikibase:timePrecision ?{name}timePrecision ;
  467. wikibase:timeTimezone ?{name}timeZone ;
  468. wikibase:timeCalendarModel ?{name}timeCalendar ] . }
  469. hint:Prior hint:rangeSafe true;""".replace('{name}', self.name)
  470. def get_group_by(self):
  471. return self.get_select()
  472. def format_8(self, value, locale):
  473. # precision: less than a year
  474. return value
  475. def format_9(self, value, locale):
  476. year = int(value)
  477. # precision: year
  478. if year < 1584:
  479. if year < 0:
  480. return str(year - 1)
  481. return str(year)
  482. timestamp = isoparse(value)
  483. return format_date(timestamp, format='yyyy', locale=locale)
  484. def format_10(self, value, locale):
  485. # precision: month
  486. timestamp = isoparse(value)
  487. return format_date(timestamp, format='MMMM y', locale=locale)
  488. def format_11(self, value, locale):
  489. # precision: day
  490. timestamp = isoparse(value)
  491. return format_date(timestamp, format='full', locale=locale)
  492. def format_13(self, value, locale):
  493. timestamp = isoparse(value)
  494. # precision: minute
  495. return get_datetime_format(format, locale=locale) \
  496. .replace("'", "") \
  497. .replace('{0}', format_time(timestamp, 'full', tzinfo=None,
  498. locale=locale)) \
  499. .replace('{1}', format_date(timestamp, 'short', locale=locale))
  500. def format_14(self, value, locale):
  501. # precision: second.
  502. return format_datetime(isoparse(value), format='full', locale=locale)
  503. DATE_FORMAT = {
  504. '0': ('format_8', 1000000000),
  505. '1': ('format_8', 100000000),
  506. '2': ('format_8', 10000000),
  507. '3': ('format_8', 1000000),
  508. '4': ('format_8', 100000),
  509. '5': ('format_8', 10000),
  510. '6': ('format_8', 1000),
  511. '7': ('format_8', 100),
  512. '8': ('format_8', 10),
  513. '9': ('format_9', 1), # year
  514. '10': ('format_10', 1), # month
  515. '11': ('format_11', 0), # day
  516. '12': ('format_13', 0), # hour (not supported by babel, display minute)
  517. '13': ('format_13', 0), # minute
  518. '14': ('format_14', 0) # second
  519. }
  520. def get_str(self, result, language):
  521. value = result.get(self.name)
  522. if value == '' or value is None:
  523. return None
  524. precision = result.get(self.name + 'timePrecision')
  525. date_format = WDDateAttribute.DATE_FORMAT.get(precision)
  526. if date_format is not None:
  527. format_method = getattr(self, date_format[0])
  528. precision = date_format[1]
  529. try:
  530. if precision >= 1:
  531. t = value.split('-')
  532. if value.startswith('-'):
  533. value = '-' + t[1]
  534. else:
  535. value = t[0]
  536. return format_method(value, language)
  537. except Exception:
  538. return value
  539. return value
  540. def debug_explain_wikidata_query(query, method='GET'):
  541. if method == 'GET':
  542. http_response = get(SPARQL_EXPLAIN_URL + '&' + urlencode({'query': query}), headers=get_headers())
  543. else:
  544. http_response = post(SPARQL_EXPLAIN_URL, data={'query': query}, headers=get_headers())
  545. http_response.raise_for_status()
  546. return http_response.content
  547. def init(engine_settings=None):
  548. # WIKIDATA_PROPERTIES : add unit symbols
  549. WIKIDATA_PROPERTIES.update(WIKIDATA_UNITS)
  550. # WIKIDATA_PROPERTIES : add property labels
  551. wikidata_property_names = []
  552. for attribute in get_attributes('en'):
  553. if type(attribute) in (WDAttribute, WDAmountAttribute, WDURLAttribute, WDDateAttribute, WDLabelAttribute):
  554. if attribute.name not in WIKIDATA_PROPERTIES:
  555. wikidata_property_names.append("wd:" + attribute.name)
  556. query = QUERY_PROPERTY_NAMES.replace('%ATTRIBUTES%', " ".join(wikidata_property_names))
  557. jsonresponse = send_wikidata_query(query)
  558. for result in jsonresponse.get('results', {}).get('bindings', {}):
  559. name = result['name']['value']
  560. lang = result['name']['xml:lang']
  561. entity_id = result['item']['value'].replace('http://www.wikidata.org/entity/', '')
  562. WIKIDATA_PROPERTIES[(entity_id, lang)] = name.capitalize()