wikidata.py 26 KB

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