@@ -1,33 +1,57 @@
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
9−from urllib import urlencode
10from lxml.html import fromstring
19from lxml.html import fromstring
11−
20+from urllib import urlencode
13logger = logger.getChild('wikidata')
22logger = logger.getChild('wikidata')
14result_count = 1
23result_count = 1
15wikidata_host = 'https://www.wikidata.org'
26wikidata_host = 'https://www.wikidata.org'
16url_search = wikidata_host \
27url_search = wikidata_host \
17 + '/wiki/Special:ItemDisambiguation?{query}'
28 + '/wiki/Special:ItemDisambiguation?{query}'
19wikidata_api = wikidata_host + '/w/api.php'
30wikidata_api = wikidata_host + '/w/api.php'
20url_detail = wikidata_api\
31url_detail = wikidata_api\
21− + '?action=wbgetentities&format=json'\
32+ + '?action=parse&format=json&{query}'\
22− + '&props=labels%7Cinfo%7Csitelinks'\
33+ + '&redirects=1&prop=text%7Cdisplaytitle%7Clanglinks%7Crevid'\
23− + '%7Csitelinks%2Furls%7Cdescriptions%7Cclaims'\
34+ + '&disableeditsection=1&disabletidy=1&preview=1§ionpreview=1&disabletoc=1&utf8=1&formatversion=2'
25url_map = 'https://www.openstreetmap.org/'\
36url_map = 'https://www.openstreetmap.org/'\
26 + '?lat={latitude}&lon={longitude}&zoom={zoom}&layers=M'
37 + '?lat={latitude}&lon={longitude}&zoom={zoom}&layers=M'
27−url_entity_label = wikidata_api\
38+url_image = 'https://commons.wikimedia.org/wiki/Special:FilePath/{filename}?width=500'
28− + '?action=wbgetentities&format=json&props=labels&{query}'
30wikidata_ids_xpath = '//div/ul[@class="wikibase-disambiguation"]/li/a/@title'
41wikidata_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")]'
33def request(query, params):
57def request(query, params):
@@ -50,13 +74,13 @@ def response(resp):
50 if language == 'all':
74 if language == 'all':
51 language = 'en'
75 language = 'en'
53− url = url_detail.format(query=urlencode({'ids': '|'.join(wikidata_ids),
77+ # TODO: make requests asynchronous to avoid timeout when result_count > 1
54− 'languages': language + '|en'}))
56− htmlresponse = get(url)
57− jsonresponse = json.loads(htmlresponse.content)
58 for wikidata_id in wikidata_ids[:result_count]:
78 for wikidata_id in wikidata_ids[:result_count]:
79+ url = url_detail.format(query=urlencode({'page': wikidata_id,
80+ 'uselang': language}))
81+ htmlresponse = get(url)
82+ jsonresponse = loads(htmlresponse.content)
59− results = results + getDetail(jsonresponse, wikidata_id, language, resp.search_params['language'])
83+ results += getDetail(jsonresponse, wikidata_id, language, resp.search_params['language'])
61 return results
85 return results
@@ -66,125 +90,194 @@ def getDetail(jsonresponse, wikidata_id, language, locale):
67 attributes = []
91 attributes = []
93+ title = jsonresponse.get('parse', {}).get('displaytitle', {})
69− result = jsonresponse.get('entities', {}).get(wikidata_id, {})
94+ result = jsonresponse.get('parse', {}).get('text', {})
71− title = result.get('labels', {}).get(language, {}).get('value', None)
96+ if not title or not result:
73− title = result.get('labels', {}).get('en', {}).get('value', None)
75 return results
97 return results
77− description = result\
99+ title = fromstring(title)
78− .get('descriptions', {})\
100+ for elem in title.xpath(language_fallback_xpath):
79− .get(language, {})\
101+ elem.getparent().remove(elem)
80− .get('value', None)
102+ title = extract_text(title.xpath(title_xpath))
82− if description is None:
104+ result = fromstring(result)
83− description = result\
105+ for elem in result.xpath(language_fallback_xpath):
84− .get('descriptions', {})\
106+ elem.getparent().remove(elem)
88− claims = result.get('claims', {})
108+ description = extract_text(result.xpath(description_xpath))
89− official_website = get_string(claims, 'P856', None)
90− if official_website is not None:
91− urls.append({'title': get_label('P856', language), 'url': official_website})
92− results.append({'title': title, 'url': official_website})
94− wikipedia_link_count = 0
110+ # URLS
95− wikipedia_link = get_wikilink(result, language + 'wiki')
96− wikipedia_link_count += add_url(urls,
97− 'Wikipedia (' + language + ')',
100− wikipedia_en_link = get_wikilink(result, 'enwiki')
101− wikipedia_link_count += add_url(urls,
104− if wikipedia_link_count == 0:
105− misc_language = get_wiki_firstlanguage(result, 'wiki')
106− if misc_language is not None:
108− 'Wikipedia (' + misc_language + ')',
109− get_wikilink(result, misc_language + 'wiki'))
111− if language != 'en':
112+ # official website
112− add_url(urls,
113+ add_url(urls, result, 'P856', results=results)
113− 'Wiki voyage (' + language + ')',
114− get_wikilink(result, language + 'wikivoyage'))
116− add_url(urls,
115+ # wikipedia
117− 'Wiki voyage (en)',
116+ wikipedia_link_count = 0
118− 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})
120 if language != 'en':
123 if language != 'en':
121− add_url(urls,
124+ wikipedia_en_link = get_wikilink(result, 'enwiki')
122− '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')
123− get_wikilink(result, language + 'wikiquote'))
135+ add_url(urls, result, default_label='Wikiquote (' + language + ')', link_type=language + 'wikiquote')
124−
136+ add_url(urls, result, default_label='Wikimedia Commons', link_type='commonswiki')
126− 'Wikiquote (en)',
138+ add_url(urls, result, 'P625', 'OpenStreetMap', link_type='geo')
127− get_wikilink(result, 'enwikiquote'))
139+
129− add_url(urls,
141+ add_url(urls, result, 'P434', 'MusicBrainz', 'http://musicbrainz.org/artist/')
131− get_wikilink(result, 'commonswiki'))
135− get_label('P625', language),
136− get_geolink(claims, 'P625', None))
140− 'https://www.wikidata.org/wiki/'
141− + wikidata_id + '?uselang=' + language)
143− musicbrainz_work_id = get_string(claims, 'P435')
144− if musicbrainz_work_id is not None:
147− 'http://musicbrainz.org/work/'
142+ add_url(urls, result, 'P435', 'MusicBrainz', 'http://musicbrainz.org/work/')
148− + musicbrainz_work_id)
150− musicbrainz_artist_id = get_string(claims, 'P434')
151− if musicbrainz_artist_id is not None:
154− 'http://musicbrainz.org/artist/'
155− + musicbrainz_artist_id)
157− musicbrainz_release_group_id = get_string(claims, 'P436')
158− if musicbrainz_release_group_id is not None:
161− 'http://musicbrainz.org/release-group/'
143+ add_url(urls, result, 'P436', 'MusicBrainz', 'http://musicbrainz.org/release-group/')
162− + musicbrainz_release_group_id)
164− musicbrainz_label_id = get_string(claims, 'P966')
165− if musicbrainz_label_id is not None:
168− 'http://musicbrainz.org/label/'
144+ add_url(urls, result, 'P966', 'MusicBrainz', 'http://musicbrainz.org/label/')
169− + musicbrainz_label_id)
145+
171− # musicbrainz_area_id = get_string(claims, 'P982')
147+ add_url(urls, result, 'P345', 'IMDb', 'https://www.imdb.com/', link_type='imdb')
172− # P1407 MusicBrainz series ID
148+ # source code repository
173− # P1004 MusicBrainz place ID
149+ add_url(urls, result, 'P1324')
174− # P1330 MusicBrainz instrument ID
150+ # blog
175− # P1407 MusicBrainz series ID
151+ add_url(urls, result, 'P1581')
176−
152+ # social media links
177− postal_code = get_string(claims, 'P281', None)
153+ add_url(urls, result, 'P2397', 'YouTube', 'https://www.youtube.com/channel/')
178− if postal_code is not None:
154+ add_url(urls, result, 'P1651', 'YouTube', 'https://www.youtube.com/watch?v=')
179− attributes.append({'label': get_label('P281', language), 'value': postal_code})
155+ add_url(urls, result, 'P2002', 'Twitter', 'https://twitter.com/')
180−
156+ add_url(urls, result, 'P2013', 'Facebook', 'https://facebook.com/')
181− date_of_birth = get_time(claims, 'P569', locale, None)
157+ add_url(urls, result, 'P2003', 'Instagram', 'https://instagram.com/')
182− if date_of_birth is not None:
158+
183− attributes.append({'label': get_label('P569', language), 'value': date_of_birth})
159+ urls.append({'title': 'Wikidata',
184−
160+ 'url': 'https://www.wikidata.org/wiki/'
185− date_of_death = get_time(claims, 'P570', locale, None)
161+ + wikidata_id + '?uselang=' + language})
186− if date_of_death is not None:
162+
187− attributes.append({'label': get_label('P570', language), 'value': date_of_death})
163+ # INFOBOX ATTRIBUTES (ROWS)
166+ add_attribute(attributes, result, 'P571', date=True)
168+ add_attribute(attributes, result, 'P576', date=True)
170+ add_attribute(attributes, result, 'P580', date=True)
172+ add_attribute(attributes, result, 'P582', date=True)
175+ add_attribute(attributes, result, 'P569', date=True)
177+ add_attribute(attributes, result, 'P570', date=True)
180+ add_attribute(attributes, result, 'P27')
182+ add_attribute(attributes, result, 'P495')
184+ add_attribute(attributes, result, 'P17')
186+ add_attribute(attributes, result, 'Q180')
190+ add_attribute(attributes, result, 'P36', trim=True)
192+ add_attribute(attributes, result, 'P35', trim=True)
193+ # head of government
194+ add_attribute(attributes, result, 'P6', trim=True)
195+ # type of government
196+ add_attribute(attributes, result, 'P122')
198+ add_attribute(attributes, result, 'P37')
200+ add_attribute(attributes, result, 'P1082', trim=True)
202+ add_attribute(attributes, result, 'P2046')
204+ add_attribute(attributes, result, 'P38')
206+ add_attribute(attributes, result, 'P2048')
209+ # platform (videogames)
210+ add_attribute(attributes, result, 'P400')
212+ add_attribute(attributes, result, 'P50')
214+ add_attribute(attributes, result, 'P170')
216+ add_attribute(attributes, result, 'P57')
218+ add_attribute(attributes, result, 'P175')
220+ add_attribute(attributes, result, 'P178')
222+ add_attribute(attributes, result, 'P162')
224+ add_attribute(attributes, result, 'P176')
226+ add_attribute(attributes, result, 'P58')
227+ # production company
228+ add_attribute(attributes, result, 'P272')
230+ add_attribute(attributes, result, 'P264')
232+ add_attribute(attributes, result, 'P123')
234+ add_attribute(attributes, result, 'P86')
236+ add_attribute(attributes, result, 'P577', date=True)
238+ add_attribute(attributes, result, 'P136')
240+ add_attribute(attributes, result, 'P364')
242+ add_attribute(attributes, result, 'Q33057')
244+ add_attribute(attributes, result, 'P275')
245+ # programming language
246+ add_attribute(attributes, result, 'P277')
248+ add_attribute(attributes, result, 'P348', trim=True)
249+ # narrative location
250+ add_attribute(attributes, result, 'P840')
253+ # number of speakers
254+ add_attribute(attributes, result, 'P1098')
256+ add_attribute(attributes, result, 'P282')
258+ add_attribute(attributes, result, 'P1018')
260+ add_attribute(attributes, result, 'P218')
264+ add_attribute(attributes, result, 'P169', trim=True)
266+ add_attribute(attributes, result, 'P112')
267+ # legal form (company/organization)
268+ add_attribute(attributes, result, 'P1454')
270+ add_attribute(attributes, result, 'P225')
272+ add_attribute(attributes, result, 'P274')
273+ # winner (sports/contests)
274+ add_attribute(attributes, result, 'P1346')
276+ add_attribute(attributes, result, 'P1120')
278+ add_attribute(attributes, result, 'P498')
280+ image = add_image(result)
189 if len(attributes) == 0 and len(urls) == 2 and len(description) == 0:
282 if len(attributes) == 0 and len(urls) == 2 and len(description) == 0:
190 results.append({
283 results.append({
@@ -197,6 +290,7 @@ def getDetail(jsonresponse, wikidata_id, language, locale):
197 'infobox': title,
290 'infobox': title,
198 'id': wikipedia_link,
291 'id': wikipedia_link,
199 'content': description,
292 'content': description,
200 'attributes': attributes,
294 'attributes': attributes,
201 'urls': urls
295 'urls': urls
@@ -204,92 +298,149 @@ def getDetail(jsonresponse, wikidata_id, language, locale):
204 return results
298 return results
207−def add_url(urls, title, url):
301+# only returns first match
208− if url is not None:
302+def add_image(result):
209− urls.append({'title': title, 'url': url})
303+ # P18: image, P154: logo, P242: map, P41: flag, P2716: collage, P2910: icon
210− return 1
304+ property_ids = ['P18', 'P154', 'P242', 'P41', 'P2716', 'P2910']
306+ for property_id in property_ids:
307+ image = result.xpath(property_xpath.replace('{propertyid}', property_id))
309+ image_name = image[0].xpath(value_xpath)
310+ image_src = url_image.replace('{filename}', extract_text(image_name[0]))
314+# setting trim will only returned high ranked rows OR the first row
315+def add_attribute(attributes, result, property_id, default_label=None, date=False, trim=False):
316+ attribute = result.xpath(property_xpath.replace('{propertyid}', property_id))
320+ label = default_label
322+ label = extract_text(attribute[0].xpath(label_xpath))
326+ # remove calendar name
327+ calendar_name = attribute[0].xpath(calendar_name_xpath)
328+ for calendar in calendar_name:
329+ calendar.getparent().remove(calendar)
334+ for row in attribute[0].xpath(property_row_xpath):
335+ if not first_value or not trim or row.xpath(preferred_rank_xpath):
337+ value = row.xpath(value_xpath)
340+ value = extract_text(value)
342+ # save first value in case no ranked row is found
343+ if trim and not first_value:
346+ # to avoid duplicate values
347+ if value not in values:
348+ concat_values += value + ", "
349+ values.append(value)
351+ if trim and not values:
352+ attributes.append({'label': label,
353+ 'value': first_value})
355+ attributes.append({'label': label,
356+ 'value': concat_values[:-2]})
359+# requires property_id unless it's a wiki link (defined in link_type)
360+def add_url(urls, result, property_id=None, default_label=None, url_prefix=None, results=None, link_type=None):
363+ # wiki links don't have property in wikidata page
364+ if link_type and 'wiki' in link_type:
365+ links.append(get_wikilink(result, link_type))
212− return 0
367+ dom_element = result.xpath(property_xpath.replace('{propertyid}', property_id))
369+ dom_element = dom_element[0]
370+ if not default_label:
371+ label = extract_text(dom_element.xpath(label_xpath))
373+ if link_type == 'geo':
374+ links.append(get_geolink(dom_element))
376+ elif link_type == 'imdb':
377+ links.append(get_imdblink(dom_element, url_prefix))
380+ url_results = dom_element.xpath(url_xpath)
381+ for link in url_results:
382+ if link is not None:
384+ link = url_prefix + extract_text(link)
386+ link = extract_text(link)
392+ urls.append({'title': default_label or label,
394+ if results is not None:
395+ results.append({'title': default_label or label,
399+def get_imdblink(result, url_prefix):
400+ imdb_id = result.xpath(value_xpath)
402+ imdb_id = extract_text(imdb_id)
403+ id_prefix = imdb_id[:2]
404+ if id_prefix == 'tt':
405+ url = url_prefix + 'title/' + imdb_id
406+ elif id_prefix == 'nm':
407+ url = url_prefix + 'name/' + imdb_id
408+ elif id_prefix == 'ch':
409+ url = url_prefix + 'character/' + imdb_id
410+ elif id_prefix == 'co':
411+ url = url_prefix + 'company/' + imdb_id
412+ elif id_prefix == 'ev':
413+ url = url_prefix + 'event/' + imdb_id
215−def get_mainsnak(claims, propertyName):
419+def get_geolink(result):
216− propValue = claims.get(propertyName, {})
420+ coordinates = result.xpath(value_xpath)
217− if len(propValue) == 0:
421+ if not coordinates:
218 return None
422 return None
219−
423+ coordinates = extract_text(coordinates[0])
220− propValue = propValue[0].get('mainsnak', None)
424+ latitude, longitude = coordinates.split(',')
221− return propValue
425+
222−
426+ # convert to decimal
223−
427+ lat = int(latitude[:latitude.find(u'°')])
224−def get_string(claims, propertyName, defaultValue=None):
428+ if latitude.find('\'') >= 0:
225− propValue = claims.get(propertyName, {})
429+ lat += int(latitude[latitude.find(u'°') + 1:latitude.find('\'')] or 0) / 60.0
226− if len(propValue) == 0:
430+ if latitude.find('"') >= 0:
227− return defaultValue
431+ lat += float(latitude[latitude.find('\'') + 1:latitude.find('"')] or 0) / 3600.0
228−
432+ if latitude.find('S') >= 0:
229− result = []
433+ lat *= -1
230− for e in propValue:
434+ lon = int(longitude[:longitude.find(u'°')])
231− mainsnak = e.get('mainsnak', {})
435+ if longitude.find('\'') >= 0:
232−
436+ lon += int(longitude[longitude.find(u'°') + 1:longitude.find('\'')] or 0) / 60.0
233− datavalue = mainsnak.get('datavalue', {})
437+ if longitude.find('"') >= 0:
234− if datavalue is not None:
438+ lon += float(longitude[longitude.find('\'') + 1:longitude.find('"')] or 0) / 3600.0
235− result.append(datavalue.get('value', ''))
439+ if longitude.find('W') >= 0:
237− if len(result) == 0:
441+
238− return defaultValue
442+ # TODO: get precision
240− # TODO handle multiple urls
244−def get_time(claims, propertyName, locale, defaultValue=None):
245− propValue = claims.get(propertyName, {})
246− if len(propValue) == 0:
251− mainsnak = e.get('mainsnak', {})
253− datavalue = mainsnak.get('datavalue', {})
254− if datavalue is not None:
255− value = datavalue.get('value', '')
256− result.append(value.get('time', ''))
258− if len(result) == 0:
259− date_string = defaultValue
261− date_string = ', '.join(result)
264− parsed_date = datetime.strptime(date_string, "+%Y-%m-%dT%H:%M:%SZ")
266− if date_string.startswith('-'):
267− return date_string.split('T')[0]
269− parsed_date = dateutil_parse(date_string, fuzzy=False, default=False)
271− logger.debug('could not parse date %s', date_string)
272− return date_string.split('T')[0]
274− return format_date_by_locale(parsed_date, locale)
277−def get_geolink(claims, propertyName, defaultValue=''):
278− mainsnak = get_mainsnak(claims, propertyName)
280− if mainsnak is None:
283− datatype = mainsnak.get('datatype', '')
284− datavalue = mainsnak.get('datavalue', {})
286− if datatype != 'globe-coordinate':
289− value = datavalue.get('value', {})
291− precision = value.get('precision', 0.0002)
443+ precision = 0.0002
293 # there is no zoom information, deduce from precision (error prone)
444 # there is no zoom information, deduce from precision (error prone)
294 # samples :
445 # samples :
295 # 13 --> 5
446 # 13 --> 5
@@ -305,39 +456,20 @@ def get_geolink(claims, propertyName, defaultValue=''):
305 zoom = int(15 - precision * 8.8322 + precision * precision * 0.625447)
456 zoom = int(15 - precision * 8.8322 + precision * precision * 0.625447)
307 url = url_map\
458 url = url_map\
308− .replace('{latitude}', str(value.get('latitude', 0)))\
459+ .replace('{latitude}', str(lat))\
309− .replace('{longitude}', str(value.get('longitude', 0)))\
460+ .replace('{longitude}', str(lon))\
310 .replace('{zoom}', str(zoom))
461 .replace('{zoom}', str(zoom))
312 return url
463 return url
315def get_wikilink(result, wikiid):
466def get_wikilink(result, wikiid):
316− url = result.get('sitelinks', {}).get(wikiid, {}).get('url', None)
467+ url = result.xpath(wikilink_xpath.replace('{wikiid}', wikiid))
317− if url is None:
468+ if not url:
318− return url
469+ return None
319− elif url.startswith('http://'):
471+ if url.startswith('http://'):
320 url = url.replace('http://', 'https://')
472 url = url.replace('http://', 'https://')
321 elif url.startswith('//'):
473 elif url.startswith('//'):
322 url = 'https:' + url
474 url = 'https:' + url
323 return url
475 return url
326−def get_wiki_firstlanguage(result, wikipatternid):
327− for k in result.get('sitelinks', {}).keys():
328− if k.endswith(wikipatternid) and len(k) == (2 + len(wikipatternid)):
333−def get_label(entity_id, language):
334− url = url_entity_label.format(query=urlencode({'ids': entity_id,
335− 'languages': language + '|en'}))
338− jsonresponse = json.loads(response.text)
339− label = jsonresponse.get('entities', {}).get(entity_id, {}).get('labels', {}).get(language, {}).get('value', None)
341− label = jsonresponse['entities'][entity_id]['labels']['en']['value']