wikidata.py 27 KB

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