wikidata.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  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/thumb/"
  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_size = img_src.replace(_IMG_SRC_DEFAULT_URL_PREFIX, "").split("?", 1)[1]
  175. img_src_size = img_src_size[img_src_size.index("=") + 1 : img_src_size.index("&")]
  176. img_src_name_md5 = md5(img_src_name.encode("utf-8")).hexdigest()
  177. img_src = (
  178. _IMG_SRC_NEW_URL_PREFIX
  179. + img_src_name_md5[0]
  180. + "/"
  181. + img_src_name_md5[0:2]
  182. + "/"
  183. + img_src_name
  184. + "/"
  185. + img_src_size
  186. + "px-"
  187. + img_src_name
  188. )
  189. logger.debug('get_thumbnail() redirected: %s', img_src)
  190. return img_src
  191. def get_results(attribute_result, attributes, language):
  192. results = []
  193. infobox_title = attribute_result.get('itemLabel')
  194. infobox_id = attribute_result['item']
  195. infobox_id_lang = None
  196. infobox_urls = []
  197. infobox_attributes = []
  198. infobox_content = attribute_result.get('itemDescription', [])
  199. img_src = None
  200. img_src_priority = 100
  201. for attribute in attributes:
  202. value = attribute.get_str(attribute_result, language)
  203. if value is not None and value != '':
  204. attribute_type = type(attribute)
  205. if attribute_type in (WDURLAttribute, WDArticle):
  206. # get_select() method : there is group_concat(distinct ...;separator=", ")
  207. # split the value here
  208. for url in value.split(', '):
  209. infobox_urls.append({'title': attribute.get_label(language), 'url': url, **attribute.kwargs})
  210. # "normal" results (not infobox) include official website and Wikipedia links.
  211. if attribute.kwargs.get('official') or attribute_type == WDArticle:
  212. results.append({'title': infobox_title, 'url': url})
  213. # update the infobox_id with the wikipedia URL
  214. # first the local wikipedia URL, and as fallback the english wikipedia URL
  215. if attribute_type == WDArticle and (
  216. (attribute.language == 'en' and infobox_id_lang is None) or attribute.language != 'en'
  217. ):
  218. infobox_id_lang = attribute.language
  219. infobox_id = url
  220. elif attribute_type == WDImageAttribute:
  221. # this attribute is an image.
  222. # replace the current image only the priority is lower
  223. # (the infobox contain only one image).
  224. if attribute.priority < img_src_priority:
  225. img_src = get_thumbnail(value)
  226. img_src_priority = attribute.priority
  227. elif attribute_type == WDGeoAttribute:
  228. # geocoordinate link
  229. # use the area to get the OSM zoom
  230. # Note: ignre the unit (must be km² otherwise the calculation is wrong)
  231. # Should use normalized value p:P2046/psn:P2046/wikibase:quantityAmount
  232. area = attribute_result.get('P2046')
  233. osm_zoom = area_to_osm_zoom(area) if area else 19
  234. url = attribute.get_geo_url(attribute_result, osm_zoom=osm_zoom)
  235. if url:
  236. infobox_urls.append({'title': attribute.get_label(language), 'url': url, 'entity': attribute.name})
  237. else:
  238. infobox_attributes.append(
  239. {'label': attribute.get_label(language), 'value': value, 'entity': attribute.name}
  240. )
  241. if infobox_id:
  242. infobox_id = replace_http_by_https(infobox_id)
  243. # add the wikidata URL at the end
  244. infobox_urls.append({'title': 'Wikidata', 'url': attribute_result['item']})
  245. if img_src is None and len(infobox_attributes) == 0 and len(infobox_urls) == 1 and len(infobox_content) == 0:
  246. results.append({'url': infobox_urls[0]['url'], 'title': infobox_title, 'content': infobox_content})
  247. else:
  248. results.append(
  249. {
  250. 'infobox': infobox_title,
  251. 'id': infobox_id,
  252. 'content': infobox_content,
  253. 'img_src': img_src,
  254. 'urls': infobox_urls,
  255. 'attributes': infobox_attributes,
  256. }
  257. )
  258. return results
  259. def get_query(query, language):
  260. attributes = get_attributes(language)
  261. select = [a.get_select() for a in attributes]
  262. where = list(filter(lambda s: len(s) > 0, [a.get_where() for a in attributes]))
  263. wikibase_label = list(filter(lambda s: len(s) > 0, [a.get_wikibase_label() for a in attributes]))
  264. group_by = list(filter(lambda s: len(s) > 0, [a.get_group_by() for a in attributes]))
  265. query = (
  266. QUERY_TEMPLATE.replace('%QUERY%', sparql_string_escape(query))
  267. .replace('%SELECT%', ' '.join(select))
  268. .replace('%WHERE%', '\n '.join(where))
  269. .replace('%WIKIBASE_LABELS%', '\n '.join(wikibase_label))
  270. .replace('%GROUP_BY%', ' '.join(group_by))
  271. .replace('%LANGUAGE%', language)
  272. )
  273. return query, attributes
  274. def get_attributes(language):
  275. attributes = []
  276. def add_value(name):
  277. attributes.append(WDAttribute(name))
  278. def add_amount(name):
  279. attributes.append(WDAmountAttribute(name))
  280. def add_label(name):
  281. attributes.append(WDLabelAttribute(name))
  282. def add_url(name, url_id=None, **kwargs):
  283. attributes.append(WDURLAttribute(name, url_id, kwargs))
  284. def add_image(name, url_id=None, priority=1):
  285. attributes.append(WDImageAttribute(name, url_id, priority))
  286. def add_date(name):
  287. attributes.append(WDDateAttribute(name))
  288. # Dates
  289. for p in [
  290. 'P571', # inception date
  291. 'P576', # dissolution date
  292. 'P580', # start date
  293. 'P582', # end date
  294. 'P569', # date of birth
  295. 'P570', # date of death
  296. 'P619', # date of spacecraft launch
  297. 'P620',
  298. ]: # date of spacecraft landing
  299. add_date(p)
  300. for p in [
  301. 'P27', # country of citizenship
  302. 'P495', # country of origin
  303. 'P17', # country
  304. 'P159',
  305. ]: # headquarters location
  306. add_label(p)
  307. # Places
  308. for p in [
  309. 'P36', # capital
  310. 'P35', # head of state
  311. 'P6', # head of government
  312. 'P122', # basic form of government
  313. 'P37',
  314. ]: # official language
  315. add_label(p)
  316. add_value('P1082') # population
  317. add_amount('P2046') # area
  318. add_amount('P281') # postal code
  319. add_label('P38') # currency
  320. add_amount('P2048') # heigth (building)
  321. # Media
  322. for p in [
  323. 'P400', # platform (videogames, computing)
  324. 'P50', # author
  325. 'P170', # creator
  326. 'P57', # director
  327. 'P175', # performer
  328. 'P178', # developer
  329. 'P162', # producer
  330. 'P176', # manufacturer
  331. 'P58', # screenwriter
  332. 'P272', # production company
  333. 'P264', # record label
  334. 'P123', # publisher
  335. 'P449', # original network
  336. 'P750', # distributed by
  337. 'P86',
  338. ]: # composer
  339. add_label(p)
  340. add_date('P577') # publication date
  341. add_label('P136') # genre (music, film, artistic...)
  342. add_label('P364') # original language
  343. add_value('P212') # ISBN-13
  344. add_value('P957') # ISBN-10
  345. add_label('P275') # copyright license
  346. add_label('P277') # programming language
  347. add_value('P348') # version
  348. add_label('P840') # narrative location
  349. # Languages
  350. add_value('P1098') # number of speakers
  351. add_label('P282') # writing system
  352. add_label('P1018') # language regulatory body
  353. add_value('P218') # language code (ISO 639-1)
  354. # Other
  355. add_label('P169') # ceo
  356. add_label('P112') # founded by
  357. add_label('P1454') # legal form (company, organization)
  358. add_label('P137') # operator (service, facility, ...)
  359. add_label('P1029') # crew members (tripulation)
  360. add_label('P225') # taxon name
  361. add_value('P274') # chemical formula
  362. add_label('P1346') # winner (sports, contests, ...)
  363. add_value('P1120') # number of deaths
  364. add_value('P498') # currency code (ISO 4217)
  365. # URL
  366. add_url('P856', official=True) # official website
  367. attributes.append(WDArticle(language)) # wikipedia (user language)
  368. if not language.startswith('en'):
  369. attributes.append(WDArticle('en')) # wikipedia (english)
  370. add_url('P1324') # source code repository
  371. add_url('P1581') # blog
  372. add_url('P434', url_id='musicbrainz_artist')
  373. add_url('P435', url_id='musicbrainz_work')
  374. add_url('P436', url_id='musicbrainz_release_group')
  375. add_url('P966', url_id='musicbrainz_label')
  376. add_url('P345', url_id='imdb_id')
  377. add_url('P2397', url_id='youtube_channel')
  378. add_url('P1651', url_id='youtube_video')
  379. add_url('P2002', url_id='twitter_profile')
  380. add_url('P2013', url_id='facebook_profile')
  381. add_url('P2003', url_id='instagram_profile')
  382. # Map
  383. attributes.append(WDGeoAttribute('P625'))
  384. # Image
  385. add_image('P15', priority=1, url_id='wikimedia_image') # route map
  386. add_image('P242', priority=2, url_id='wikimedia_image') # locator map
  387. add_image('P154', priority=3, url_id='wikimedia_image') # logo
  388. add_image('P18', priority=4, url_id='wikimedia_image') # image
  389. add_image('P41', priority=5, url_id='wikimedia_image') # flag
  390. add_image('P2716', priority=6, url_id='wikimedia_image') # collage
  391. add_image('P2910', priority=7, url_id='wikimedia_image') # icon
  392. return attributes
  393. class WDAttribute:
  394. __slots__ = ('name',)
  395. def __init__(self, name):
  396. self.name = name
  397. def get_select(self):
  398. return '(group_concat(distinct ?{name};separator=", ") as ?{name}s)'.replace('{name}', self.name)
  399. def get_label(self, language):
  400. return get_label_for_entity(self.name, language)
  401. def get_where(self):
  402. return "OPTIONAL { ?item wdt:{name} ?{name} . }".replace('{name}', self.name)
  403. def get_wikibase_label(self):
  404. return ""
  405. def get_group_by(self):
  406. return ""
  407. def get_str(self, result, language):
  408. return result.get(self.name + 's')
  409. def __repr__(self):
  410. return '<' + str(type(self).__name__) + ':' + self.name + '>'
  411. class WDAmountAttribute(WDAttribute):
  412. def get_select(self):
  413. return '?{name} ?{name}Unit'.replace('{name}', self.name)
  414. def get_where(self):
  415. return """ OPTIONAL { ?item p:{name} ?{name}Node .
  416. ?{name}Node rdf:type wikibase:BestRank ; ps:{name} ?{name} .
  417. OPTIONAL { ?{name}Node psv:{name}/wikibase:quantityUnit ?{name}Unit. } }""".replace(
  418. '{name}', self.name
  419. )
  420. def get_group_by(self):
  421. return self.get_select()
  422. def get_str(self, result, language):
  423. value = result.get(self.name)
  424. unit = result.get(self.name + "Unit")
  425. if unit is not None:
  426. unit = unit.replace('http://www.wikidata.org/entity/', '')
  427. return value + " " + get_label_for_entity(unit, language)
  428. return value
  429. class WDArticle(WDAttribute):
  430. __slots__ = 'language', 'kwargs'
  431. def __init__(self, language, kwargs=None):
  432. super().__init__('wikipedia')
  433. self.language = language
  434. self.kwargs = kwargs or {}
  435. def get_label(self, language):
  436. # language parameter is ignored
  437. return "Wikipedia ({language})".replace('{language}', self.language)
  438. def get_select(self):
  439. return "?article{language} ?articleName{language}".replace('{language}', self.language)
  440. def get_where(self):
  441. return """OPTIONAL { ?article{language} schema:about ?item ;
  442. schema:inLanguage "{language}" ;
  443. schema:isPartOf <https://{language}.wikipedia.org/> ;
  444. schema:name ?articleName{language} . }""".replace(
  445. '{language}', self.language
  446. )
  447. def get_group_by(self):
  448. return self.get_select()
  449. def get_str(self, result, language):
  450. key = 'article{language}'.replace('{language}', self.language)
  451. return result.get(key)
  452. class WDLabelAttribute(WDAttribute):
  453. def get_select(self):
  454. return '(group_concat(distinct ?{name}Label;separator=", ") as ?{name}Labels)'.replace('{name}', self.name)
  455. def get_where(self):
  456. return "OPTIONAL { ?item wdt:{name} ?{name} . }".replace('{name}', self.name)
  457. def get_wikibase_label(self):
  458. return "?{name} rdfs:label ?{name}Label .".replace('{name}', self.name)
  459. def get_str(self, result, language):
  460. return result.get(self.name + 'Labels')
  461. class WDURLAttribute(WDAttribute):
  462. HTTP_WIKIMEDIA_IMAGE = 'http://commons.wikimedia.org/wiki/Special:FilePath/'
  463. __slots__ = 'url_id', 'kwargs'
  464. def __init__(self, name, url_id=None, kwargs=None):
  465. super().__init__(name)
  466. self.url_id = url_id
  467. self.kwargs = kwargs
  468. def get_str(self, result, language):
  469. value = result.get(self.name + 's')
  470. if self.url_id and value is not None and value != '':
  471. value = value.split(',')[0]
  472. url_id = self.url_id
  473. if value.startswith(WDURLAttribute.HTTP_WIKIMEDIA_IMAGE):
  474. value = value[len(WDURLAttribute.HTTP_WIKIMEDIA_IMAGE) :]
  475. url_id = 'wikimedia_image'
  476. return get_external_url(url_id, value)
  477. return value
  478. class WDGeoAttribute(WDAttribute):
  479. def get_label(self, language):
  480. return "OpenStreetMap"
  481. def get_select(self):
  482. return "?{name}Lat ?{name}Long".replace('{name}', self.name)
  483. def get_where(self):
  484. return """OPTIONAL { ?item p:{name}/psv:{name} [
  485. wikibase:geoLatitude ?{name}Lat ;
  486. wikibase:geoLongitude ?{name}Long ] }""".replace(
  487. '{name}', self.name
  488. )
  489. def get_group_by(self):
  490. return self.get_select()
  491. def get_str(self, result, language):
  492. latitude = result.get(self.name + 'Lat')
  493. longitude = result.get(self.name + 'Long')
  494. if latitude and longitude:
  495. return latitude + ' ' + longitude
  496. return None
  497. def get_geo_url(self, result, osm_zoom=19):
  498. latitude = result.get(self.name + 'Lat')
  499. longitude = result.get(self.name + 'Long')
  500. if latitude and longitude:
  501. return get_earth_coordinates_url(latitude, longitude, osm_zoom)
  502. return None
  503. class WDImageAttribute(WDURLAttribute):
  504. __slots__ = ('priority',)
  505. def __init__(self, name, url_id=None, priority=100):
  506. super().__init__(name, url_id)
  507. self.priority = priority
  508. class WDDateAttribute(WDAttribute):
  509. def get_select(self):
  510. return '?{name} ?{name}timePrecision ?{name}timeZone ?{name}timeCalendar'.replace('{name}', self.name)
  511. def get_where(self):
  512. # To remove duplicate, add
  513. # FILTER NOT EXISTS { ?item p:{name}/psv:{name}/wikibase:timeValue ?{name}bis FILTER (?{name}bis < ?{name}) }
  514. # this filter is too slow, so the response function ignore duplicate results
  515. # (see the seen_entities variable)
  516. return """OPTIONAL { ?item p:{name}/psv:{name} [
  517. wikibase:timeValue ?{name} ;
  518. wikibase:timePrecision ?{name}timePrecision ;
  519. wikibase:timeTimezone ?{name}timeZone ;
  520. wikibase:timeCalendarModel ?{name}timeCalendar ] . }
  521. hint:Prior hint:rangeSafe true;""".replace(
  522. '{name}', self.name
  523. )
  524. def get_group_by(self):
  525. return self.get_select()
  526. def format_8(self, value, locale):
  527. # precision: less than a year
  528. return value
  529. def format_9(self, value, locale):
  530. year = int(value)
  531. # precision: year
  532. if year < 1584:
  533. if year < 0:
  534. return str(year - 1)
  535. return str(year)
  536. timestamp = isoparse(value)
  537. return format_date(timestamp, format='yyyy', locale=locale)
  538. def format_10(self, value, locale):
  539. # precision: month
  540. timestamp = isoparse(value)
  541. return format_date(timestamp, format='MMMM y', locale=locale)
  542. def format_11(self, value, locale):
  543. # precision: day
  544. timestamp = isoparse(value)
  545. return format_date(timestamp, format='full', locale=locale)
  546. def format_13(self, value, locale):
  547. timestamp = isoparse(value)
  548. # precision: minute
  549. return (
  550. get_datetime_format(format, locale=locale)
  551. .replace("'", "")
  552. .replace('{0}', format_time(timestamp, 'full', tzinfo=None, locale=locale))
  553. .replace('{1}', format_date(timestamp, 'short', locale=locale))
  554. )
  555. def format_14(self, value, locale):
  556. # precision: second.
  557. return format_datetime(isoparse(value), format='full', locale=locale)
  558. DATE_FORMAT = {
  559. '0': ('format_8', 1000000000),
  560. '1': ('format_8', 100000000),
  561. '2': ('format_8', 10000000),
  562. '3': ('format_8', 1000000),
  563. '4': ('format_8', 100000),
  564. '5': ('format_8', 10000),
  565. '6': ('format_8', 1000),
  566. '7': ('format_8', 100),
  567. '8': ('format_8', 10),
  568. '9': ('format_9', 1), # year
  569. '10': ('format_10', 1), # month
  570. '11': ('format_11', 0), # day
  571. '12': ('format_13', 0), # hour (not supported by babel, display minute)
  572. '13': ('format_13', 0), # minute
  573. '14': ('format_14', 0), # second
  574. }
  575. def get_str(self, result, language):
  576. value = result.get(self.name)
  577. if value == '' or value is None:
  578. return None
  579. precision = result.get(self.name + 'timePrecision')
  580. date_format = WDDateAttribute.DATE_FORMAT.get(precision)
  581. if date_format is not None:
  582. format_method = getattr(self, date_format[0])
  583. precision = date_format[1]
  584. try:
  585. if precision >= 1:
  586. t = value.split('-')
  587. if value.startswith('-'):
  588. value = '-' + t[1]
  589. else:
  590. value = t[0]
  591. return format_method(value, language)
  592. except Exception:
  593. return value
  594. return value
  595. def debug_explain_wikidata_query(query, method='GET'):
  596. if method == 'GET':
  597. http_response = get(SPARQL_EXPLAIN_URL + '&' + urlencode({'query': query}), headers=get_headers())
  598. else:
  599. http_response = post(SPARQL_EXPLAIN_URL, data={'query': query}, headers=get_headers())
  600. http_response.raise_for_status()
  601. return http_response.content
  602. def init(engine_settings=None):
  603. # WIKIDATA_PROPERTIES : add unit symbols
  604. WIKIDATA_PROPERTIES.update(WIKIDATA_UNITS)
  605. # WIKIDATA_PROPERTIES : add property labels
  606. wikidata_property_names = []
  607. for attribute in get_attributes('en'):
  608. if type(attribute) in (WDAttribute, WDAmountAttribute, WDURLAttribute, WDDateAttribute, WDLabelAttribute):
  609. if attribute.name not in WIKIDATA_PROPERTIES:
  610. wikidata_property_names.append("wd:" + attribute.name)
  611. query = QUERY_PROPERTY_NAMES.replace('%ATTRIBUTES%', " ".join(wikidata_property_names))
  612. jsonresponse = send_wikidata_query(query)
  613. for result in jsonresponse.get('results', {}).get('bindings', {}):
  614. name = result['name']['value']
  615. lang = result['name']['xml:lang']
  616. entity_id = result['item']['value'].replace('http://www.wikidata.org/entity/', '')
  617. WIKIDATA_PROPERTIES[(entity_id, lang)] = name.capitalize()