logo

searx

My custom branche(s) on searx, a meta-search engine git clone https://hacktivis.me/git/searx.git

wikidata.py (17152B)


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