wikidata.py 25 KB

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