@@ -1,56 +1,86 @@
1−import json
1+# -*- coding: utf-8 -*-
5+ @website https://wikidata.org
6+ @provide-api yes (https://wikidata.org/w/api.php)
8+ @using-api partially (most things require scraping)
10+ @stable no (html can change)
3from searx import logger
14from searx import logger
4from searx.poolrequests import get
15from searx.poolrequests import get
5−from searx.utils import format_date_by_locale
16+from searx.engines.xpath import extract_text
7−from datetime import datetime
18+from json import loads
8−from dateutil.parser import parse as dateutil_parse
19+from lxml.html import fromstring
9from urllib import urlencode
20from urllib import urlencode
12logger = logger.getChild('wikidata')
22logger = logger.getChild('wikidata')
13result_count = 1
23result_count = 1
14wikidata_host = 'https://www.wikidata.org'
26wikidata_host = 'https://www.wikidata.org'
27+url_search = wikidata_host \
28+ + '/wiki/Special:ItemDisambiguation?{query}'
15wikidata_api = wikidata_host + '/w/api.php'
30wikidata_api = wikidata_host + '/w/api.php'
16−url_search = wikidata_api \
17− + '?action=query&list=search&format=json'\
18− + '&srnamespace=0&srprop=sectiontitle&{query}'
19url_detail = wikidata_api\
31url_detail = wikidata_api\
20− + '?action=wbgetentities&format=json'\
32+ + '?action=parse&format=json&{query}'\
21− + '&props=labels%7Cinfo%7Csitelinks'\
33+ + '&redirects=1&prop=text%7Cdisplaytitle%7Clanglinks%7Crevid'\
22− + '%7Csitelinks%2Furls%7Cdescriptions%7Cclaims'\
34+ + '&disableeditsection=1&disabletidy=1&preview=1§ionpreview=1&disabletoc=1&utf8=1&formatversion=2'
24url_map = 'https://www.openstreetmap.org/'\
36url_map = 'https://www.openstreetmap.org/'\
25 + '?lat={latitude}&lon={longitude}&zoom={zoom}&layers=M'
37 + '?lat={latitude}&lon={longitude}&zoom={zoom}&layers=M'
38+url_image = 'https://commons.wikimedia.org/wiki/Special:FilePath/{filename}?width=500&height=400'
41+wikidata_ids_xpath = '//div/ul[@class="wikibase-disambiguation"]/li/a/@title'
42+title_xpath = '//*[contains(@class,"wikibase-title-label")]'
43+description_xpath = '//div[contains(@class,"wikibase-entitytermsview-heading-description")]'
44+property_xpath = '//div[@id="{propertyid}"]'
45+label_xpath = './/div[contains(@class,"wikibase-statementgroupview-property-label")]/a'
46+url_xpath = './/a[contains(@class,"external free") or contains(@class, "wb-external-id")]'
47+wikilink_xpath = './/ul[contains(@class,"wikibase-sitelinklistview-listview")]'\
48+ + '/li[contains(@data-wb-siteid,"{wikiid}")]//a/@href'
49+property_row_xpath = './/div[contains(@class,"wikibase-statementview")]'
50+preferred_rank_xpath = './/span[contains(@class,"wikibase-rankselector-preferred")]'
51+value_xpath = './/div[contains(@class,"wikibase-statementview-mainsnak")]'\
52+ + '/*/div[contains(@class,"wikibase-snakview-value")]'
53+language_fallback_xpath = '//sup[contains(@class,"wb-language-fallback-indicator")]'
54+calendar_name_xpath = './/sup[contains(@class,"wb-calendar-name")]'
28def request(query, params):
57def request(query, params):
58+ language = params['language'].split('_')[0]
59+ if language == 'all':
29 params['url'] = url_search.format(
62 params['url'] = url_search.format(
30− query=urlencode({'srsearch': query,
63+ query=urlencode({'label': query,
31− 'srlimit': result_count}))
64+ 'language': language}))
32 return params
65 return params
35def response(resp):
68def response(resp):
36 results = []
69 results = []
37− search_res = json.loads(resp.text)
70+ html = fromstring(resp.content)
39− wikidata_ids = set()
71+ wikidata_ids = html.xpath(wikidata_ids_xpath)
40− for r in search_res.get('query', {}).get('search', {}):
41− wikidata_ids.add(r.get('title', ''))
43 language = resp.search_params['language'].split('_')[0]
73 language = resp.search_params['language'].split('_')[0]
44 if language == 'all':
74 if language == 'all':
45 language = 'en'
75 language = 'en'
77+ # TODO: make requests asynchronous to avoid timeout when result_count > 1
78+ for wikidata_id in wikidata_ids[:result_count]:
47− url = url_detail.format(query=urlencode({'ids': '|'.join(wikidata_ids),
79+ url = url_detail.format(query=urlencode({'page': wikidata_id,
48− 'languages': language + '|en'}))
80+ 'uselang': language}))
50− htmlresponse = get(url)
81+ htmlresponse = get(url)
51− jsonresponse = json.loads(htmlresponse.content)
82+ jsonresponse = loads(htmlresponse.content)
52− for wikidata_id in wikidata_ids:
53− results = results + getDetail(jsonresponse, wikidata_id, language, resp.search_params['language'])
83+ results += getDetail(jsonresponse, wikidata_id, language, resp.search_params['language'])
55 return results
85 return results
@@ -60,124 +90,206 @@ def getDetail(jsonresponse, wikidata_id, language, locale):
61 attributes = []
91 attributes = []
93+ title = jsonresponse.get('parse', {}).get('displaytitle', {})
63− result = jsonresponse.get('entities', {}).get(wikidata_id, {})
94+ result = jsonresponse.get('parse', {}).get('text', {})
65− title = result.get('labels', {}).get(language, {}).get('value', None)
96+ if not title or not result:
67− title = result.get('labels', {}).get('en', {}).get('value', None)
69 return results
97 return results
71− description = result\
99+ title = fromstring(title)
72− .get('descriptions', {})\
100+ for elem in title.xpath(language_fallback_xpath):
73− .get(language, {})\
101+ elem.getparent().remove(elem)
74− .get('value', None)
102+ title = extract_text(title.xpath(title_xpath))
76− if description is None:
104+ result = fromstring(result)
77− description = result\
105+ for elem in result.xpath(language_fallback_xpath):
78− .get('descriptions', {})\
106+ elem.getparent().remove(elem)
82− claims = result.get('claims', {})
108+ description = extract_text(result.xpath(description_xpath))
83− official_website = get_string(claims, 'P856', None)
84− if official_website is not None:
85− urls.append({'title': 'Official site', 'url': official_website})
86− results.append({'title': title, 'url': official_website})
88− wikipedia_link_count = 0
110+ # URLS
89− wikipedia_link = get_wikilink(result, language + 'wiki')
90− wikipedia_link_count += add_url(urls,
91− 'Wikipedia (' + language + ')',
94− wikipedia_en_link = get_wikilink(result, 'enwiki')
95− wikipedia_link_count += add_url(urls,
98− if wikipedia_link_count == 0:
99− misc_language = get_wiki_firstlanguage(result, 'wiki')
100− if misc_language is not None:
102− 'Wikipedia (' + misc_language + ')',
103− get_wikilink(result, misc_language + 'wiki'))
105− if language != 'en':
112+ # official website
106− add_url(urls,
113+ add_url(urls, result, 'P856', results=results)
107− 'Wiki voyage (' + language + ')',
108− get_wikilink(result, language + 'wikivoyage'))
110− add_url(urls,
115+ # wikipedia
111− 'Wiki voyage (en)',
116+ wikipedia_link_count = 0
112− get_wikilink(result, 'enwikivoyage'))
117+ wikipedia_link = get_wikilink(result, language + 'wiki')
119+ wikipedia_link_count += 1
120+ urls.append({'title': 'Wikipedia (' + language + ')',
121+ 'url': wikipedia_link})
114 if language != 'en':
123 if language != 'en':
115− add_url(urls,
124+ wikipedia_en_link = get_wikilink(result, 'enwiki')
116− 'Wikiquote (' + language + ')',
125+ if wikipedia_en_link:
126+ wikipedia_link_count += 1
127+ urls.append({'title': 'Wikipedia (en)',
128+ 'url': wikipedia_en_link})
130+ # TODO: get_wiki_firstlanguage
131+ # if wikipedia_link_count == 0:
134+ add_url(urls, result, default_label='Wikivoyage (' + language + ')', link_type=language + 'wikivoyage')
117− get_wikilink(result, language + 'wikiquote'))
135+ add_url(urls, result, default_label='Wikiquote (' + language + ')', link_type=language + 'wikiquote')
118−
136+ add_url(urls, result, default_label='Wikimedia Commons', link_type='commonswiki')
120− 'Wikiquote (en)',
138+ add_url(urls, result, 'P625', 'OpenStreetMap', link_type='geo')
121− get_wikilink(result, 'enwikiquote'))
139+
123− add_url(urls,
141+ add_url(urls, result, 'P434', 'MusicBrainz', 'http://musicbrainz.org/artist/')
125− get_wikilink(result, 'commonswiki'))
129− get_geolink(claims, 'P625', None))
133− 'https://www.wikidata.org/wiki/'
134− + wikidata_id + '?uselang=' + language)
136− musicbrainz_work_id = get_string(claims, 'P435')
137− if musicbrainz_work_id is not None:
140− 'http://musicbrainz.org/work/'
142+ add_url(urls, result, 'P435', 'MusicBrainz', 'http://musicbrainz.org/work/')
141− + musicbrainz_work_id)
143− musicbrainz_artist_id = get_string(claims, 'P434')
144− if musicbrainz_artist_id is not None:
147− 'http://musicbrainz.org/artist/'
148− + musicbrainz_artist_id)
150− musicbrainz_release_group_id = get_string(claims, 'P436')
151− if musicbrainz_release_group_id is not None:
154− 'http://musicbrainz.org/release-group/'
143+ add_url(urls, result, 'P436', 'MusicBrainz', 'http://musicbrainz.org/release-group/')
155− + musicbrainz_release_group_id)
144+ add_url(urls, result, 'P966', 'MusicBrainz', 'http://musicbrainz.org/label/')
157− musicbrainz_label_id = get_string(claims, 'P966')
146+ # IMDb
158− if musicbrainz_label_id is not None:
147+ add_url(urls, result, 'P345', 'IMDb', 'https://www.imdb.com/', link_type='imdb')
159− add_url(urls,
148+ # source code repository
160− 'MusicBrainz',
149+ add_url(urls, result, 'P1324')
161− 'http://musicbrainz.org/label/'
150+ # blog
162− + musicbrainz_label_id)
151+ add_url(urls, result, 'P1581')
163−
152+ # social media links
164− # musicbrainz_area_id = get_string(claims, 'P982')
153+ add_url(urls, result, 'P2397', 'YouTube', 'https://www.youtube.com/channel/')
165− # P1407 MusicBrainz series ID
154+ add_url(urls, result, 'P1651', 'YouTube', 'https://www.youtube.com/watch?v=')
166− # P1004 MusicBrainz place ID
155+ add_url(urls, result, 'P2002', 'Twitter', 'https://twitter.com/')
167− # P1330 MusicBrainz instrument ID
156+ add_url(urls, result, 'P2013', 'Facebook', 'https://facebook.com/')
168− # P1407 MusicBrainz series ID
157+ add_url(urls, result, 'P2003', 'Instagram', 'https://instagram.com/')
170− postal_code = get_string(claims, 'P281', None)
159+ urls.append({'title': 'Wikidata',
171− if postal_code is not None:
160+ 'url': 'https://www.wikidata.org/wiki/'
172− attributes.append({'label': 'Postal code(s)', 'value': postal_code})
161+ + wikidata_id + '?uselang=' + language})
174− date_of_birth = get_time(claims, 'P569', locale, None)
163+ # INFOBOX ATTRIBUTES (ROWS)
175− if date_of_birth is not None:
164+
176− attributes.append({'label': 'Date of birth', 'value': date_of_birth})
165+ # DATES
177−
166+ # inception date
178− date_of_death = get_time(claims, 'P570', locale, None)
167+ add_attribute(attributes, result, 'P571', date=True)
179− if date_of_death is not None:
168+ # dissolution date
180− attributes.append({'label': 'Date of death', 'value': date_of_death})
169+ add_attribute(attributes, result, 'P576', date=True)
171+ add_attribute(attributes, result, 'P580', date=True)
173+ add_attribute(attributes, result, 'P582', date=True)
175+ add_attribute(attributes, result, 'P569', date=True)
177+ add_attribute(attributes, result, 'P570', date=True)
178+ # date of spacecraft launch
179+ add_attribute(attributes, result, 'P619', date=True)
180+ # date of spacecraft landing
181+ add_attribute(attributes, result, 'P620', date=True)
184+ add_attribute(attributes, result, 'P27')
186+ add_attribute(attributes, result, 'P495')
188+ add_attribute(attributes, result, 'P17')
190+ add_attribute(attributes, result, 'Q180')
194+ add_attribute(attributes, result, 'P36', trim=True)
196+ add_attribute(attributes, result, 'P35', trim=True)
197+ # head of government
198+ add_attribute(attributes, result, 'P6', trim=True)
199+ # type of government
200+ add_attribute(attributes, result, 'P122')
202+ add_attribute(attributes, result, 'P37')
204+ add_attribute(attributes, result, 'P1082', trim=True)
206+ add_attribute(attributes, result, 'P2046')
208+ add_attribute(attributes, result, 'P38', trim=True)
210+ add_attribute(attributes, result, 'P2048')
213+ # platform (videogames)
214+ add_attribute(attributes, result, 'P400')
216+ add_attribute(attributes, result, 'P50')
218+ add_attribute(attributes, result, 'P170')
220+ add_attribute(attributes, result, 'P57')
222+ add_attribute(attributes, result, 'P175')
224+ add_attribute(attributes, result, 'P178')
226+ add_attribute(attributes, result, 'P162')
228+ add_attribute(attributes, result, 'P176')
230+ add_attribute(attributes, result, 'P58')
231+ # production company
232+ add_attribute(attributes, result, 'P272')
234+ add_attribute(attributes, result, 'P264')
236+ add_attribute(attributes, result, 'P123')
238+ add_attribute(attributes, result, 'P449')
240+ add_attribute(attributes, result, 'P750')
242+ add_attribute(attributes, result, 'P86')
244+ add_attribute(attributes, result, 'P577', date=True)
246+ add_attribute(attributes, result, 'P136')
248+ add_attribute(attributes, result, 'P364')
250+ add_attribute(attributes, result, 'Q33057')
252+ add_attribute(attributes, result, 'P275')
253+ # programming language
254+ add_attribute(attributes, result, 'P277')
256+ add_attribute(attributes, result, 'P348', trim=True)
257+ # narrative location
258+ add_attribute(attributes, result, 'P840')
261+ # number of speakers
262+ add_attribute(attributes, result, 'P1098')
264+ add_attribute(attributes, result, 'P282')
266+ add_attribute(attributes, result, 'P1018')
268+ add_attribute(attributes, result, 'P218')
272+ add_attribute(attributes, result, 'P169', trim=True)
274+ add_attribute(attributes, result, 'P112')
275+ # legal form (company/organization)
276+ add_attribute(attributes, result, 'P1454')
278+ add_attribute(attributes, result, 'P137')
279+ # crew members (tripulation)
280+ add_attribute(attributes, result, 'P1029')
282+ add_attribute(attributes, result, 'P225')
284+ add_attribute(attributes, result, 'P274')
285+ # winner (sports/contests)
286+ add_attribute(attributes, result, 'P1346')
288+ add_attribute(attributes, result, 'P1120')
290+ add_attribute(attributes, result, 'P498')
292+ image = add_image(result)
182 if len(attributes) == 0 and len(urls) == 2 and len(description) == 0:
294 if len(attributes) == 0 and len(urls) == 2 and len(description) == 0:
183 results.append({
295 results.append({
@@ -190,6 +302,7 @@ def getDetail(jsonresponse, wikidata_id, language, locale):
190 'infobox': title,
302 'infobox': title,
191 'id': wikipedia_link,
303 'id': wikipedia_link,
192 'content': description,
304 'content': description,
193 'attributes': attributes,
306 'attributes': attributes,
194 'urls': urls
307 'urls': urls
@@ -197,92 +310,151 @@ def getDetail(jsonresponse, wikidata_id, language, locale):
197 return results
310 return results
200−def add_url(urls, title, url):
313+# only returns first match
201− if url is not None:
314+def add_image(result):
202− urls.append({'title': title, 'url': url})
315+ # P15: route map, P242: locator map, P154: logo, P18: image, P242: map, P41: flag, P2716: collage, P2910: icon
316+ property_ids = ['P15', 'P242', 'P154', 'P18', 'P242', 'P41', 'P2716', 'P2910']
318+ for property_id in property_ids:
319+ image = result.xpath(property_xpath.replace('{propertyid}', property_id))
321+ image_name = image[0].xpath(value_xpath)
322+ image_src = url_image.replace('{filename}', extract_text(image_name[0]))
203− return 1
323+ return image_src
326+# setting trim will only returned high ranked rows OR the first row
327+def add_attribute(attributes, result, property_id, default_label=None, date=False, trim=False):
328+ attribute = result.xpath(property_xpath.replace('{propertyid}', property_id))
332+ label = default_label
334+ label = extract_text(attribute[0].xpath(label_xpath))
335+ label = label[0].upper() + label[1:]
339+ # remove calendar name
340+ calendar_name = attribute[0].xpath(calendar_name_xpath)
341+ for calendar in calendar_name:
342+ calendar.getparent().remove(calendar)
347+ for row in attribute[0].xpath(property_row_xpath):
348+ if not first_value or not trim or row.xpath(preferred_rank_xpath):
350+ value = row.xpath(value_xpath)
353+ value = extract_text(value)
355+ # save first value in case no ranked row is found
356+ if trim and not first_value:
359+ # to avoid duplicate values
360+ if value not in values:
361+ concat_values += value + ", "
362+ values.append(value)
364+ if trim and not values:
365+ attributes.append({'label': label,
366+ 'value': first_value})
368+ attributes.append({'label': label,
369+ 'value': concat_values[:-2]})
372+# requires property_id unless it's a wiki link (defined in link_type)
373+def add_url(urls, result, property_id=None, default_label=None, url_prefix=None, results=None, link_type=None):
376+ # wiki links don't have property in wikidata page
377+ if link_type and 'wiki' in link_type:
378+ links.append(get_wikilink(result, link_type))
380+ dom_element = result.xpath(property_xpath.replace('{propertyid}', property_id))
382+ dom_element = dom_element[0]
383+ if not default_label:
384+ label = extract_text(dom_element.xpath(label_xpath))
385+ label = label[0].upper() + label[1:]
387+ if link_type == 'geo':
388+ links.append(get_geolink(dom_element))
390+ elif link_type == 'imdb':
391+ links.append(get_imdblink(dom_element, url_prefix))
394+ url_results = dom_element.xpath(url_xpath)
395+ for link in url_results:
396+ if link is not None:
398+ link = url_prefix + extract_text(link)
400+ link = extract_text(link)
406+ urls.append({'title': default_label or label,
408+ if results is not None:
409+ results.append({'title': default_label or label,
413+def get_imdblink(result, url_prefix):
414+ imdb_id = result.xpath(value_xpath)
416+ imdb_id = extract_text(imdb_id)
417+ id_prefix = imdb_id[:2]
418+ if id_prefix == 'tt':
419+ url = url_prefix + 'title/' + imdb_id
420+ elif id_prefix == 'nm':
421+ url = url_prefix + 'name/' + imdb_id
422+ elif id_prefix == 'ch':
423+ url = url_prefix + 'character/' + imdb_id
424+ elif id_prefix == 'co':
425+ url = url_prefix + 'company/' + imdb_id
426+ elif id_prefix == 'ev':
427+ url = url_prefix + 'event/' + imdb_id
205− return 0
430+ return url
208−def get_mainsnak(claims, propertyName):
433+def get_geolink(result):
209− propValue = claims.get(propertyName, {})
434+ coordinates = result.xpath(value_xpath)
210− if len(propValue) == 0:
435+ if not coordinates:
211 return None
436 return None
212−
437+ coordinates = extract_text(coordinates[0])
213− propValue = propValue[0].get('mainsnak', None)
438+ latitude, longitude = coordinates.split(',')
214− return propValue
439+
215−
440+ # convert to decimal
216−
441+ lat = int(latitude[:latitude.find(u'°')])
217−def get_string(claims, propertyName, defaultValue=None):
442+ if latitude.find('\'') >= 0:
218− propValue = claims.get(propertyName, {})
443+ lat += int(latitude[latitude.find(u'°') + 1:latitude.find('\'')] or 0) / 60.0
219− if len(propValue) == 0:
444+ if latitude.find('"') >= 0:
220− return defaultValue
445+ lat += float(latitude[latitude.find('\'') + 1:latitude.find('"')] or 0) / 3600.0
221−
446+ if latitude.find('S') >= 0:
222− result = []
447+ lat *= -1
223− for e in propValue:
448+ lon = int(longitude[:longitude.find(u'°')])
224− mainsnak = e.get('mainsnak', {})
449+ if longitude.find('\'') >= 0:
225−
450+ lon += int(longitude[longitude.find(u'°') + 1:longitude.find('\'')] or 0) / 60.0
226− datavalue = mainsnak.get('datavalue', {})
451+ if longitude.find('"') >= 0:
227− if datavalue is not None:
452+ lon += float(longitude[longitude.find('\'') + 1:longitude.find('"')] or 0) / 3600.0
228− result.append(datavalue.get('value', ''))
453+ if longitude.find('W') >= 0:
230− if len(result) == 0:
455+
231− return defaultValue
456+ # TODO: get precision
233− # TODO handle multiple urls
237−def get_time(claims, propertyName, locale, defaultValue=None):
238− propValue = claims.get(propertyName, {})
239− if len(propValue) == 0:
244− mainsnak = e.get('mainsnak', {})
246− datavalue = mainsnak.get('datavalue', {})
247− if datavalue is not None:
248− value = datavalue.get('value', '')
249− result.append(value.get('time', ''))
251− if len(result) == 0:
252− date_string = defaultValue
254− date_string = ', '.join(result)
257− parsed_date = datetime.strptime(date_string, "+%Y-%m-%dT%H:%M:%SZ")
259− if date_string.startswith('-'):
260− return date_string.split('T')[0]
262− parsed_date = dateutil_parse(date_string, fuzzy=False, default=False)
264− logger.debug('could not parse date %s', date_string)
265− return date_string.split('T')[0]
267− return format_date_by_locale(parsed_date, locale)
270−def get_geolink(claims, propertyName, defaultValue=''):
271− mainsnak = get_mainsnak(claims, propertyName)
273− if mainsnak is None:
276− datatype = mainsnak.get('datatype', '')
277− datavalue = mainsnak.get('datavalue', {})
279− if datatype != 'globe-coordinate':
282− value = datavalue.get('value', {})
284− precision = value.get('precision', 0.0002)
457+ precision = 0.0002
286 # there is no zoom information, deduce from precision (error prone)
458 # there is no zoom information, deduce from precision (error prone)
287 # samples :
459 # samples :
288 # 13 --> 5
460 # 13 --> 5
@@ -298,26 +470,20 @@ def get_geolink(claims, propertyName, defaultValue=''):
298 zoom = int(15 - precision * 8.8322 + precision * precision * 0.625447)
470 zoom = int(15 - precision * 8.8322 + precision * precision * 0.625447)
300 url = url_map\
472 url = url_map\
301− .replace('{latitude}', str(value.get('latitude', 0)))\
473+ .replace('{latitude}', str(lat))\
302− .replace('{longitude}', str(value.get('longitude', 0)))\
474+ .replace('{longitude}', str(lon))\
303 .replace('{zoom}', str(zoom))
475 .replace('{zoom}', str(zoom))
305 return url
477 return url
308def get_wikilink(result, wikiid):
480def get_wikilink(result, wikiid):
309− url = result.get('sitelinks', {}).get(wikiid, {}).get('url', None)
481+ url = result.xpath(wikilink_xpath.replace('{wikiid}', wikiid))
310− if url is None:
482+ if not url:
311− return url
483+ return None
312− elif url.startswith('http://'):
485+ if url.startswith('http://'):
313 url = url.replace('http://', 'https://')
486 url = url.replace('http://', 'https://')
314 elif url.startswith('//'):
487 elif url.startswith('//'):
315 url = 'https:' + url
488 url = 'https:' + url
316 return url
489 return url
319−def get_wiki_firstlanguage(result, wikipatternid):
320− for k in result.get('sitelinks', {}).keys():
321− if k.endswith(wikipatternid) and len(k) == (2 + len(wikipatternid)):