wikidata.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. # -*- coding: utf-8 -*-
  2. """
  3. Wikidata
  4. @website https://wikidata.org
  5. @provide-api yes (https://wikidata.org/w/api.php)
  6. @using-api partially (most things require scraping)
  7. @results JSON, HTML
  8. @stable no (html can change)
  9. @parse url, infobox
  10. """
  11. from searx import logger
  12. from searx.poolrequests import get
  13. from searx.engines.wikipedia import _fetch_supported_languages, supported_languages_url
  14. from searx.utils import extract_text, match_language, eval_xpath
  15. from urllib.parse import urlencode
  16. from json import loads
  17. from lxml.html import fromstring
  18. from lxml import etree
  19. logger = logger.getChild('wikidata')
  20. result_count = 1
  21. # urls
  22. wikidata_host = 'https://www.wikidata.org'
  23. url_search = wikidata_host \
  24. + '/w/index.php?{query}&ns0=1'
  25. wikidata_api = wikidata_host + '/w/api.php'
  26. url_detail = wikidata_api\
  27. + '?action=parse&format=json&{query}'\
  28. + '&redirects=1&prop=text%7Cdisplaytitle%7Cparsewarnings'\
  29. + '&disableeditsection=1&preview=1&sectionpreview=1&disabletoc=1&utf8=1&formatversion=2'
  30. url_map = 'https://www.openstreetmap.org/'\
  31. + '?lat={latitude}&lon={longitude}&zoom={zoom}&layers=M'
  32. url_image = 'https://commons.wikimedia.org/wiki/Special:FilePath/{filename}?width=500&height=400'
  33. # xpaths
  34. div_ids_xpath = '//div[@id]'
  35. wikidata_ids_xpath = '//ul[@class="mw-search-results"]/li//a/@href'
  36. title_xpath = '//*[contains(@class,"wikibase-title-label")]'
  37. description_xpath = '//div[contains(@class,"wikibase-entitytermsview-heading-description")]'
  38. label_xpath = './/div[contains(@class,"wikibase-statementgroupview-property-label")]/a'
  39. url_xpath = './/a[contains(@class,"external free") or contains(@class, "wb-external-id")]'
  40. wikilink_xpath = './/ul[contains(@class,"wikibase-sitelinklistview-listview")]'\
  41. + '/li[contains(@data-wb-siteid,"{wikiid}")]//a/@href'
  42. property_row_xpath = './/div[contains(@class,"wikibase-statementview")]'
  43. preferred_rank_xpath = './/span[contains(@class,"wikibase-rankselector-preferred")]'
  44. value_xpath = './/div[contains(@class,"wikibase-statementview-mainsnak")]'\
  45. + '/*/div[contains(@class,"wikibase-snakview-value")]'
  46. language_fallback_xpath = '//sup[contains(@class,"wb-language-fallback-indicator")]'
  47. calendar_name_xpath = './/sup[contains(@class,"wb-calendar-name")]'
  48. media_xpath = value_xpath + '//div[contains(@class,"commons-media-caption")]//a'
  49. def get_id_cache(result):
  50. id_cache = {}
  51. for e in eval_xpath(result, div_ids_xpath):
  52. id = e.get('id')
  53. if id.startswith('P'):
  54. id_cache[id] = e
  55. return id_cache
  56. def request(query, params):
  57. params['url'] = url_search.format(
  58. query=urlencode({'search': query}))
  59. return params
  60. def response(resp):
  61. results = []
  62. htmlparser = etree.HTMLParser()
  63. html = fromstring(resp.content.decode(), parser=htmlparser)
  64. search_results = eval_xpath(html, wikidata_ids_xpath)
  65. if resp.search_params['language'].split('-')[0] == 'all':
  66. language = 'en'
  67. else:
  68. language = match_language(resp.search_params['language'], supported_languages, language_aliases).split('-')[0]
  69. # TODO: make requests asynchronous to avoid timeout when result_count > 1
  70. for search_result in search_results[:result_count]:
  71. wikidata_id = search_result.split('/')[-1]
  72. url = url_detail.format(query=urlencode({'page': wikidata_id, 'uselang': language}))
  73. htmlresponse = get(url)
  74. jsonresponse = loads(htmlresponse.content.decode())
  75. results += getDetail(jsonresponse, wikidata_id, language, resp.search_params['language'], htmlparser)
  76. return results
  77. def getDetail(jsonresponse, wikidata_id, language, locale, htmlparser):
  78. results = []
  79. urls = []
  80. attributes = []
  81. title = jsonresponse.get('parse', {}).get('displaytitle', {})
  82. result = jsonresponse.get('parse', {}).get('text', {})
  83. if not title or not result:
  84. return results
  85. title = fromstring(title, parser=htmlparser)
  86. for elem in eval_xpath(title, language_fallback_xpath):
  87. elem.getparent().remove(elem)
  88. title = extract_text(eval_xpath(title, title_xpath))
  89. result = fromstring(result, parser=htmlparser)
  90. for elem in eval_xpath(result, language_fallback_xpath):
  91. elem.getparent().remove(elem)
  92. description = extract_text(eval_xpath(result, description_xpath))
  93. id_cache = get_id_cache(result)
  94. # URLS
  95. # official website
  96. add_url(urls, result, id_cache, 'P856', results=results)
  97. # wikipedia
  98. wikipedia_link_count = 0
  99. wikipedia_link = get_wikilink(result, language + 'wiki')
  100. if wikipedia_link:
  101. wikipedia_link_count += 1
  102. urls.append({'title': 'Wikipedia (' + language + ')',
  103. 'url': wikipedia_link})
  104. if language != 'en':
  105. wikipedia_en_link = get_wikilink(result, 'enwiki')
  106. if wikipedia_en_link:
  107. wikipedia_link_count += 1
  108. urls.append({'title': 'Wikipedia (en)',
  109. 'url': wikipedia_en_link})
  110. # TODO: get_wiki_firstlanguage
  111. # if wikipedia_link_count == 0:
  112. # more wikis
  113. add_url(urls, result, id_cache, default_label='Wikivoyage (' + language + ')', link_type=language + 'wikivoyage')
  114. add_url(urls, result, id_cache, default_label='Wikiquote (' + language + ')', link_type=language + 'wikiquote')
  115. add_url(urls, result, id_cache, default_label='Wikimedia Commons', link_type='commonswiki')
  116. add_url(urls, result, id_cache, 'P625', 'OpenStreetMap', link_type='geo')
  117. # musicbrainz
  118. add_url(urls, result, id_cache, 'P434', 'MusicBrainz', 'http://musicbrainz.org/artist/')
  119. add_url(urls, result, id_cache, 'P435', 'MusicBrainz', 'http://musicbrainz.org/work/')
  120. add_url(urls, result, id_cache, 'P436', 'MusicBrainz', 'http://musicbrainz.org/release-group/')
  121. add_url(urls, result, id_cache, 'P966', 'MusicBrainz', 'http://musicbrainz.org/label/')
  122. # IMDb
  123. add_url(urls, result, id_cache, 'P345', 'IMDb', 'https://www.imdb.com/', link_type='imdb')
  124. # source code repository
  125. add_url(urls, result, id_cache, 'P1324')
  126. # blog
  127. add_url(urls, result, id_cache, 'P1581')
  128. # social media links
  129. add_url(urls, result, id_cache, 'P2397', 'YouTube', 'https://www.youtube.com/channel/')
  130. add_url(urls, result, id_cache, 'P1651', 'YouTube', 'https://www.youtube.com/watch?v=')
  131. add_url(urls, result, id_cache, 'P2002', 'Twitter', 'https://twitter.com/')
  132. add_url(urls, result, id_cache, 'P2013', 'Facebook', 'https://facebook.com/')
  133. add_url(urls, result, id_cache, 'P2003', 'Instagram', 'https://instagram.com/')
  134. urls.append({'title': 'Wikidata',
  135. 'url': 'https://www.wikidata.org/wiki/'
  136. + wikidata_id + '?uselang=' + language})
  137. # INFOBOX ATTRIBUTES (ROWS)
  138. # DATES
  139. # inception date
  140. add_attribute(attributes, id_cache, 'P571', date=True)
  141. # dissolution date
  142. add_attribute(attributes, id_cache, 'P576', date=True)
  143. # start date
  144. add_attribute(attributes, id_cache, 'P580', date=True)
  145. # end date
  146. add_attribute(attributes, id_cache, 'P582', date=True)
  147. # date of birth
  148. add_attribute(attributes, id_cache, 'P569', date=True)
  149. # date of death
  150. add_attribute(attributes, id_cache, 'P570', date=True)
  151. # date of spacecraft launch
  152. add_attribute(attributes, id_cache, 'P619', date=True)
  153. # date of spacecraft landing
  154. add_attribute(attributes, id_cache, 'P620', date=True)
  155. # nationality
  156. add_attribute(attributes, id_cache, 'P27')
  157. # country of origin
  158. add_attribute(attributes, id_cache, 'P495')
  159. # country
  160. add_attribute(attributes, id_cache, 'P17')
  161. # headquarters
  162. add_attribute(attributes, id_cache, 'Q180')
  163. # PLACES
  164. # capital
  165. add_attribute(attributes, id_cache, 'P36', trim=True)
  166. # head of state
  167. add_attribute(attributes, id_cache, 'P35', trim=True)
  168. # head of government
  169. add_attribute(attributes, id_cache, 'P6', trim=True)
  170. # type of government
  171. add_attribute(attributes, id_cache, 'P122')
  172. # official language
  173. add_attribute(attributes, id_cache, 'P37')
  174. # population
  175. add_attribute(attributes, id_cache, 'P1082', trim=True)
  176. # area
  177. add_attribute(attributes, id_cache, 'P2046')
  178. # currency
  179. add_attribute(attributes, id_cache, 'P38', trim=True)
  180. # heigth (building)
  181. add_attribute(attributes, id_cache, 'P2048')
  182. # MEDIA
  183. # platform (videogames)
  184. add_attribute(attributes, id_cache, 'P400')
  185. # author
  186. add_attribute(attributes, id_cache, 'P50')
  187. # creator
  188. add_attribute(attributes, id_cache, 'P170')
  189. # director
  190. add_attribute(attributes, id_cache, 'P57')
  191. # performer
  192. add_attribute(attributes, id_cache, 'P175')
  193. # developer
  194. add_attribute(attributes, id_cache, 'P178')
  195. # producer
  196. add_attribute(attributes, id_cache, 'P162')
  197. # manufacturer
  198. add_attribute(attributes, id_cache, 'P176')
  199. # screenwriter
  200. add_attribute(attributes, id_cache, 'P58')
  201. # production company
  202. add_attribute(attributes, id_cache, 'P272')
  203. # record label
  204. add_attribute(attributes, id_cache, 'P264')
  205. # publisher
  206. add_attribute(attributes, id_cache, 'P123')
  207. # original network
  208. add_attribute(attributes, id_cache, 'P449')
  209. # distributor
  210. add_attribute(attributes, id_cache, 'P750')
  211. # composer
  212. add_attribute(attributes, id_cache, 'P86')
  213. # publication date
  214. add_attribute(attributes, id_cache, 'P577', date=True)
  215. # genre
  216. add_attribute(attributes, id_cache, 'P136')
  217. # original language
  218. add_attribute(attributes, id_cache, 'P364')
  219. # isbn
  220. add_attribute(attributes, id_cache, 'Q33057')
  221. # software license
  222. add_attribute(attributes, id_cache, 'P275')
  223. # programming language
  224. add_attribute(attributes, id_cache, 'P277')
  225. # version
  226. add_attribute(attributes, id_cache, 'P348', trim=True)
  227. # narrative location
  228. add_attribute(attributes, id_cache, 'P840')
  229. # LANGUAGES
  230. # number of speakers
  231. add_attribute(attributes, id_cache, 'P1098')
  232. # writing system
  233. add_attribute(attributes, id_cache, 'P282')
  234. # regulatory body
  235. add_attribute(attributes, id_cache, 'P1018')
  236. # language code
  237. add_attribute(attributes, id_cache, 'P218')
  238. # OTHER
  239. # ceo
  240. add_attribute(attributes, id_cache, 'P169', trim=True)
  241. # founder
  242. add_attribute(attributes, id_cache, 'P112')
  243. # legal form (company/organization)
  244. add_attribute(attributes, id_cache, 'P1454')
  245. # operator
  246. add_attribute(attributes, id_cache, 'P137')
  247. # crew members (tripulation)
  248. add_attribute(attributes, id_cache, 'P1029')
  249. # taxon
  250. add_attribute(attributes, id_cache, 'P225')
  251. # chemical formula
  252. add_attribute(attributes, id_cache, 'P274')
  253. # winner (sports/contests)
  254. add_attribute(attributes, id_cache, 'P1346')
  255. # number of deaths
  256. add_attribute(attributes, id_cache, 'P1120')
  257. # currency code
  258. add_attribute(attributes, id_cache, 'P498')
  259. image = add_image(id_cache)
  260. if len(attributes) == 0 and len(urls) == 2 and len(description) == 0:
  261. results.append({
  262. 'url': urls[0]['url'],
  263. 'title': title,
  264. 'content': description
  265. })
  266. else:
  267. results.append({
  268. 'infobox': title,
  269. 'id': wikipedia_link,
  270. 'content': description,
  271. 'img_src': image,
  272. 'attributes': attributes,
  273. 'urls': urls
  274. })
  275. return results
  276. # only returns first match
  277. def add_image(id_cache):
  278. # P15: route map, P242: locator map, P154: logo, P18: image, P242: map, P41: flag, P2716: collage, P2910: icon
  279. property_ids = ['P15', 'P242', 'P154', 'P18', 'P242', 'P41', 'P2716', 'P2910']
  280. for property_id in property_ids:
  281. image = id_cache.get(property_id, None)
  282. if image is not None:
  283. image_name = eval_xpath(image, media_xpath)
  284. image_src = url_image.replace('{filename}', extract_text(image_name[0]))
  285. return image_src
  286. # setting trim will only returned high ranked rows OR the first row
  287. def add_attribute(attributes, id_cache, property_id, default_label=None, date=False, trim=False):
  288. attribute = id_cache.get(property_id, None)
  289. if attribute is not None:
  290. if default_label:
  291. label = default_label
  292. else:
  293. label = extract_text(eval_xpath(attribute, label_xpath))
  294. label = label[0].upper() + label[1:]
  295. if date:
  296. trim = True
  297. # remove calendar name
  298. calendar_name = eval_xpath(attribute, calendar_name_xpath)
  299. for calendar in calendar_name:
  300. calendar.getparent().remove(calendar)
  301. concat_values = ""
  302. values = []
  303. first_value = None
  304. for row in eval_xpath(attribute, property_row_xpath):
  305. if not first_value or not trim or eval_xpath(row, preferred_rank_xpath):
  306. value = eval_xpath(row, value_xpath)
  307. if not value:
  308. continue
  309. value = extract_text(value)
  310. # save first value in case no ranked row is found
  311. if trim and not first_value:
  312. first_value = value
  313. else:
  314. # to avoid duplicate values
  315. if value not in values:
  316. concat_values += value + ", "
  317. values.append(value)
  318. if trim and not values:
  319. attributes.append({'label': label,
  320. 'value': first_value})
  321. else:
  322. attributes.append({'label': label,
  323. 'value': concat_values[:-2]})
  324. # requires property_id unless it's a wiki link (defined in link_type)
  325. def add_url(urls, result, id_cache, property_id=None, default_label=None, url_prefix=None, results=None,
  326. link_type=None, only_first=True):
  327. links = []
  328. # wiki links don't have property in wikidata page
  329. if link_type and 'wiki' in link_type:
  330. links.append(get_wikilink(result, link_type))
  331. else:
  332. dom_element = id_cache.get(property_id, None)
  333. if dom_element is not None:
  334. if not default_label:
  335. label = extract_text(eval_xpath(dom_element, label_xpath))
  336. label = label[0].upper() + label[1:]
  337. if link_type == 'geo':
  338. links.append(get_geolink(dom_element))
  339. elif link_type == 'imdb':
  340. links.append(get_imdblink(dom_element, url_prefix))
  341. else:
  342. url_results = eval_xpath(dom_element, url_xpath)
  343. for link in url_results:
  344. if link is not None:
  345. if url_prefix:
  346. link = url_prefix + extract_text(link)
  347. else:
  348. link = extract_text(link)
  349. links.append(link)
  350. # append urls
  351. for url in links:
  352. if url is not None:
  353. u = {'title': default_label or label, 'url': url}
  354. if property_id == 'P856':
  355. u['official'] = True
  356. u['domain'] = url.split('/')[2]
  357. urls.append(u)
  358. if results is not None:
  359. results.append(u)
  360. if only_first:
  361. break
  362. def get_imdblink(result, url_prefix):
  363. imdb_id = eval_xpath(result, value_xpath)
  364. if imdb_id:
  365. imdb_id = extract_text(imdb_id)
  366. id_prefix = imdb_id[:2]
  367. if id_prefix == 'tt':
  368. url = url_prefix + 'title/' + imdb_id
  369. elif id_prefix == 'nm':
  370. url = url_prefix + 'name/' + imdb_id
  371. elif id_prefix == 'ch':
  372. url = url_prefix + 'character/' + imdb_id
  373. elif id_prefix == 'co':
  374. url = url_prefix + 'company/' + imdb_id
  375. elif id_prefix == 'ev':
  376. url = url_prefix + 'event/' + imdb_id
  377. else:
  378. url = None
  379. return url
  380. def get_geolink(result):
  381. coordinates = eval_xpath(result, value_xpath)
  382. if not coordinates:
  383. return None
  384. coordinates = extract_text(coordinates[0])
  385. latitude, longitude = coordinates.split(',')
  386. # convert to decimal
  387. lat = int(latitude[:latitude.find('°')])
  388. if latitude.find('\'') >= 0:
  389. lat += int(latitude[latitude.find('°') + 1:latitude.find('\'')] or 0) / 60.0
  390. if latitude.find('"') >= 0:
  391. lat += float(latitude[latitude.find('\'') + 1:latitude.find('"')] or 0) / 3600.0
  392. if latitude.find('S') >= 0:
  393. lat *= -1
  394. lon = int(longitude[:longitude.find('°')])
  395. if longitude.find('\'') >= 0:
  396. lon += int(longitude[longitude.find('°') + 1:longitude.find('\'')] or 0) / 60.0
  397. if longitude.find('"') >= 0:
  398. lon += float(longitude[longitude.find('\'') + 1:longitude.find('"')] or 0) / 3600.0
  399. if longitude.find('W') >= 0:
  400. lon *= -1
  401. # TODO: get precision
  402. precision = 0.0002
  403. # there is no zoom information, deduce from precision (error prone)
  404. # samples :
  405. # 13 --> 5
  406. # 1 --> 6
  407. # 0.016666666666667 --> 9
  408. # 0.00027777777777778 --> 19
  409. # wolframalpha :
  410. # quadratic fit { {13, 5}, {1, 6}, {0.0166666, 9}, {0.0002777777,19}}
  411. # 14.1186-8.8322 x+0.625447 x^2
  412. if precision < 0.0003:
  413. zoom = 19
  414. else:
  415. zoom = int(15 - precision * 8.8322 + precision * precision * 0.625447)
  416. url = url_map\
  417. .replace('{latitude}', str(lat))\
  418. .replace('{longitude}', str(lon))\
  419. .replace('{zoom}', str(zoom))
  420. return url
  421. def get_wikilink(result, wikiid):
  422. url = eval_xpath(result, wikilink_xpath.replace('{wikiid}', wikiid))
  423. if not url:
  424. return None
  425. url = url[0]
  426. if url.startswith('http://'):
  427. url = url.replace('http://', 'https://')
  428. elif url.startswith('//'):
  429. url = 'https:' + url
  430. return url