wikidata.py 17 KB

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