wikidata.py 26 KB

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