wikidata.py 27 KB

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