wikidata.py 27 KB

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