wikidata.py 26 KB

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