2"""This module implements the Wikidata engine. Some implementations are shared
3from :ref:`wikipedia engine`.
8from typing
import TYPE_CHECKING
10from urllib.parse
import urlencode, unquote
13from dateutil.parser
import isoparse
14from babel.dates
import format_datetime, format_date, format_time, get_datetime_format
18from searx.utils import searx_useragent, get_string_replaces_function
19from searx.external_urls import get_external_url, get_earth_coordinates_url, area_to_osm_zoom
21 fetch_wikimedia_traits,
29 logger: logging.Logger
35 "website":
'https://wikidata.org/',
36 "wikidata_id":
'Q2013',
37 "official_api_documentation":
'https://query.wikidata.org/',
38 "use_official_api":
True,
39 "require_api_key":
False,
43display_type = [
"infobox"]
44"""A list of display types composed from ``infobox`` and ``list``. The latter
45one will add a hit to the result list. The first one will show a hit in the
46info box. Both values can be set, or one of the two can be set."""
50SPARQL_ENDPOINT_URL =
'https://query.wikidata.org/sparql'
51SPARQL_EXPLAIN_URL =
'https://query.wikidata.org/bigdata/namespace/wdq/sparql?explain'
52WIKIDATA_PROPERTIES = {
53 'P434':
'MusicBrainz',
54 'P435':
'MusicBrainz',
55 'P436':
'MusicBrainz',
56 'P966':
'MusicBrainz',
73SELECT ?item ?itemLabel ?itemDescription ?lat ?long %SELECT%
76 SERVICE wikibase:mwapi {
77 bd:serviceParam wikibase:endpoint "www.wikidata.org";
78 wikibase:api "EntitySearch";
80 mwapi:search "%QUERY%";
81 mwapi:language "%LANGUAGE%".
82 ?item wikibase:apiOutputItem mwapi:item.
84 hint:Prior hint:runFirst "true".
88 SERVICE wikibase:label {
89 bd:serviceParam wikibase:language "%LANGUAGE%,en".
90 ?item rdfs:label ?itemLabel .
91 ?item schema:description ?itemDescription .
96GROUP BY ?item ?itemLabel ?itemDescription ?lat ?long %GROUP_BY%
100QUERY_PROPERTY_NAMES =
"""
105 WHERE { ?item wdt:P279* wd:Q12132 }
107 VALUES ?item { %ATTRIBUTES% }
109 OPTIONAL { ?item rdfs:label ?name. }
115DUMMY_ENTITY_URLS = set(
116 "http://www.wikidata.org/entity/" + wid
for wid
in (
"Q4115189",
"Q13406268",
"Q15397819",
"Q17339402")
122sparql_string_escape = get_string_replaces_function(
137replace_http_by_https = get_string_replaces_function({
'http:':
'https:'})
142 return {
'Accept':
'application/sparql-results+json',
'User-Agent': searx_useragent()}
146 name = WIKIDATA_PROPERTIES.get(entity_id)
148 name = WIKIDATA_PROPERTIES.get((entity_id, language))
150 name = WIKIDATA_PROPERTIES.get((entity_id, language.split(
'-')[0]))
152 name = WIKIDATA_PROPERTIES.get((entity_id,
'en'))
161 http_response = get(SPARQL_ENDPOINT_URL +
'?' + urlencode({
'query': query}), headers=
get_headers())
164 http_response = post(SPARQL_ENDPOINT_URL, data={
'query': query}, headers=
get_headers())
165 if http_response.status_code != 200:
166 logger.debug(
'SPARQL endpoint error %s', http_response.content.decode())
167 logger.debug(
'request time %s', str(http_response.elapsed))
168 http_response.raise_for_status()
169 return loads(http_response.content.decode())
174 eng_tag, _wiki_netloc = get_wiki_params(params[
'searxng_locale'], traits)
175 query, attributes =
get_query(query, eng_tag)
176 logger.debug(
"request --> language %s // len(attributes): %s", eng_tag, len(attributes))
178 params[
'method'] =
'POST'
179 params[
'url'] = SPARQL_ENDPOINT_URL
180 params[
'data'] = {
'query': query}
182 params[
'language'] = eng_tag
183 params[
'attributes'] = attributes
191 jsonresponse = loads(resp.content.decode())
193 language = resp.search_params[
'language']
194 attributes = resp.search_params[
'attributes']
195 logger.debug(
"request --> language %s // len(attributes): %s", language, len(attributes))
197 seen_entities = set()
198 for result
in jsonresponse.get(
'results', {}).get(
'bindings', []):
199 attribute_result = {key: value[
'value']
for key, value
in result.items()}
200 entity_url = attribute_result[
'item']
201 if entity_url
not in seen_entities
and entity_url
not in DUMMY_ENTITY_URLS:
202 seen_entities.add(entity_url)
203 results +=
get_results(attribute_result, attributes, language)
205 logger.debug(
'The SPARQL request returns duplicate entities: %s', str(attribute_result))
210_IMG_SRC_DEFAULT_URL_PREFIX =
"https://commons.wikimedia.org/wiki/Special:FilePath/"
211_IMG_SRC_NEW_URL_PREFIX =
"https://upload.wikimedia.org/wikipedia/commons/thumb/"
215 """Get Thumbnail image from wikimedia commons
217 Images from commons.wikimedia.org are (HTTP) redirected to
218 upload.wikimedia.org. The redirected URL can be calculated by this
221 - https://stackoverflow.com/a/33691240
224 logger.debug(
'get_thumbnail(): %s', img_src)
225 if not img_src
is None and _IMG_SRC_DEFAULT_URL_PREFIX
in img_src.split()[0]:
226 img_src_name = unquote(img_src.replace(_IMG_SRC_DEFAULT_URL_PREFIX,
"").split(
"?", 1)[0].replace(
"%20",
"_"))
227 img_src_name_first = img_src_name
228 img_src_name_second = img_src_name
230 if ".svg" in img_src_name.split()[0]:
231 img_src_name_second = img_src_name +
".png"
233 img_src_size = img_src.replace(_IMG_SRC_DEFAULT_URL_PREFIX,
"").split(
"?", 1)[1]
234 img_src_size = img_src_size[img_src_size.index(
"=") + 1 : img_src_size.index(
"&")]
235 img_src_name_md5 = md5(img_src_name.encode(
"utf-8")).hexdigest()
237 _IMG_SRC_NEW_URL_PREFIX
238 + img_src_name_md5[0]
240 + img_src_name_md5[0:2]
246 + img_src_name_second
248 logger.debug(
'get_thumbnail() redirected: %s', img_src)
256 infobox_title = attribute_result.get(
'itemLabel')
257 infobox_id = attribute_result[
'item']
258 infobox_id_lang =
None
260 infobox_attributes = []
261 infobox_content = attribute_result.get(
'itemDescription', [])
265 for attribute
in attributes:
266 value = attribute.get_str(attribute_result, language)
267 if value
is not None and value !=
'':
268 attribute_type = type(attribute)
270 if attribute_type
in (WDURLAttribute, WDArticle):
273 for url
in value.split(
', '):
274 infobox_urls.append({
'title': attribute.get_label(language),
'url': url, **attribute.kwargs})
276 if "list" in display_type
and (attribute.kwargs.get(
'official')
or attribute_type == WDArticle):
277 results.append({
'title': infobox_title,
'url': url,
"content": infobox_content})
281 if attribute_type == WDArticle
and (
282 (attribute.language ==
'en' and infobox_id_lang
is None)
or attribute.language !=
'en'
284 infobox_id_lang = attribute.language
286 elif attribute_type == WDImageAttribute:
290 if attribute.priority > img_src_priority:
291 img_src = get_thumbnail(value)
292 img_src_priority = attribute.priority
293 elif attribute_type == WDGeoAttribute:
298 area = attribute_result.get(
'P2046')
299 osm_zoom = area_to_osm_zoom(area)
if area
else 19
300 url = attribute.get_geo_url(attribute_result, osm_zoom=osm_zoom)
302 infobox_urls.append({
'title': attribute.get_label(language),
'url': url,
'entity': attribute.name})
304 infobox_attributes.append(
305 {
'label': attribute.get_label(language),
'value': value,
'entity': attribute.name}
312 infobox_urls.append({
'title':
'Wikidata',
'url': attribute_result[
'item']})
315 "list" in display_type
317 and len(infobox_attributes) == 0
318 and len(infobox_urls) == 1
319 and len(infobox_content) == 0
321 results.append({
'url': infobox_urls[0][
'url'],
'title': infobox_title,
'content': infobox_content})
322 elif "infobox" in display_type:
325 'infobox': infobox_title,
327 'content': infobox_content,
329 'urls': infobox_urls,
330 'attributes': infobox_attributes,
338 select = [a.get_select()
for a
in attributes]
339 where = list(filter(
lambda s: len(s) > 0, [a.get_where()
for a
in attributes]))
340 wikibase_label = list(filter(
lambda s: len(s) > 0, [a.get_wikibase_label()
for a
in attributes]))
341 group_by = list(filter(
lambda s: len(s) > 0, [a.get_group_by()
for a
in attributes]))
343 QUERY_TEMPLATE.replace(
'%QUERY%', sparql_string_escape(query))
344 .replace(
'%SELECT%',
' '.join(select))
345 .replace(
'%WHERE%',
'\n '.join(where))
346 .replace(
'%WIKIBASE_LABELS%',
'\n '.join(wikibase_label))
347 .replace(
'%GROUP_BY%',
' '.join(group_by))
348 .replace(
'%LANGUAGE%', language)
350 return query, attributes
360 def add_amount(name):
366 def add_url(name, url_id=None, **kwargs):
369 def add_image(name, url_id=None, priority=1):
461 add_url(
'P856', official=
True)
463 if not language.startswith(
'en'):
468 add_url(
'P434', url_id=
'musicbrainz_artist')
469 add_url(
'P435', url_id=
'musicbrainz_work')
470 add_url(
'P436', url_id=
'musicbrainz_release_group')
471 add_url(
'P966', url_id=
'musicbrainz_label')
472 add_url(
'P345', url_id=
'imdb_id')
473 add_url(
'P2397', url_id=
'youtube_channel')
474 add_url(
'P1651', url_id=
'youtube_video')
475 add_url(
'P2002', url_id=
'twitter_profile')
476 add_url(
'P2013', url_id=
'facebook_profile')
477 add_url(
'P2003', url_id=
'instagram_profile')
483 add_image(
'P15', priority=1, url_id=
'wikimedia_image')
484 add_image(
'P242', priority=2, url_id=
'wikimedia_image')
485 add_image(
'P154', priority=3, url_id=
'wikimedia_image')
486 add_image(
'P18', priority=4, url_id=
'wikimedia_image')
487 add_image(
'P41', priority=5, url_id=
'wikimedia_image')
488 add_image(
'P2716', priority=6, url_id=
'wikimedia_image')
489 add_image(
'P2910', priority=7, url_id=
'wikimedia_image')
495 __slots__ = (
'name',)
501 return '(group_concat(distinct ?{name};separator=", ") as ?{name}s)'.replace(
'{name}', self.
name)
507 return "OPTIONAL { ?item wdt:{name} ?{name} . }".replace(
'{name}', self.
name)
516 return result.get(self.
name +
's')
519 return '<' + str(type(self).__name__) +
':' + self.
name +
'>'
524 return '?{name} ?{name}Unit'.replace(
'{name}', self.
namename)
527 return """ OPTIONAL { ?item p:{name} ?{name}Node .
528 ?{name}Node rdf:type wikibase:BestRank ; ps:{name} ?{name} .
529 OPTIONAL { ?{name}Node psv:{name}/wikibase:quantityUnit ?{name}Unit. } }""".replace(
538 unit = result.get(self.
namename +
"Unit")
540 unit = unit.replace(
'http://www.wikidata.org/entity/',
'')
547 __slots__ =
'language',
'kwargs'
556 return "Wikipedia ({language})".replace(
'{language}', self.
language)
559 return "?article{language} ?articleName{language}".replace(
'{language}', self.
language)
562 return """OPTIONAL { ?article{language} schema:about ?item ;
563 schema:inLanguage "{language}" ;
564 schema:isPartOf <https://{language}.wikipedia.org/> ;
565 schema:name ?articleName{language} . }""".replace(
573 key =
'article{language}'.replace(
'{language}', self.
language)
574 return result.get(key)
579 return '(group_concat(distinct ?{name}Label;separator=", ") as ?{name}Labels)'.replace(
'{name}', self.
namename)
582 return "OPTIONAL { ?item wdt:{name} ?{name} . }".replace(
'{name}', self.
namename)
585 return "?{name} rdfs:label ?{name}Label .".replace(
'{name}', self.
namename)
588 return result.get(self.
namename +
'Labels')
593 HTTP_WIKIMEDIA_IMAGE =
'http://commons.wikimedia.org/wiki/Special:FilePath/'
595 __slots__ =
'url_id',
'kwargs'
597 def __init__(self, name, url_id=None, kwargs=None):
603 value = result.get(self.
name +
's')
604 if self.
url_id and value
is not None and value !=
'':
605 value = value.split(
',')[0]
607 if value.startswith(WDURLAttribute.HTTP_WIKIMEDIA_IMAGE):
608 value = value[len(WDURLAttribute.HTTP_WIKIMEDIA_IMAGE) :]
609 url_id =
'wikimedia_image'
610 return get_external_url(url_id, value)
616 return "OpenStreetMap"
619 return "?{name}Lat ?{name}Long".replace(
'{name}', self.
namename)
622 return """OPTIONAL { ?item p:{name}/psv:{name} [
623 wikibase:geoLatitude ?{name}Lat ;
624 wikibase:geoLongitude ?{name}Long ] }""".replace(
632 latitude = result.get(self.
namename +
'Lat')
633 longitude = result.get(self.
namename +
'Long')
634 if latitude
and longitude:
635 return latitude +
' ' + longitude
639 latitude = result.get(self.
namename +
'Lat')
640 longitude = result.get(self.
namename +
'Long')
641 if latitude
and longitude:
642 return get_earth_coordinates_url(latitude, longitude, osm_zoom)
648 __slots__ = (
'priority',)
650 def __init__(self, name, url_id=None, priority=100):
657 return '?{name} ?{name}timePrecision ?{name}timeZone ?{name}timeCalendar'.replace(
'{name}', self.
namename)
664 return """OPTIONAL { ?item p:{name}/psv:{name} [
665 wikibase:timeValue ?{name} ;
666 wikibase:timePrecision ?{name}timePrecision ;
667 wikibase:timeTimezone ?{name}timeZone ;
668 wikibase:timeCalendarModel ?{name}timeCalendar ] . }
669 hint:Prior hint:rangeSafe true;""".replace(
687 timestamp = isoparse(value)
688 return format_date(timestamp, format=
'yyyy', locale=locale)
692 timestamp = isoparse(value)
693 return format_date(timestamp, format=
'MMMM y', locale=locale)
697 timestamp = isoparse(value)
698 return format_date(timestamp, format=
'full', locale=locale)
701 timestamp = isoparse(value)
704 get_datetime_format(format, locale=locale)
706 .replace(
'{0}', format_time(timestamp,
'full', tzinfo=
None, locale=locale))
707 .replace(
'{1}', format_date(timestamp,
'short', locale=locale))
712 return format_datetime(isoparse(value), format=
'full', locale=locale)
715 '0': (
'format_8', 1000000000),
716 '1': (
'format_8', 100000000),
717 '2': (
'format_8', 10000000),
718 '3': (
'format_8', 1000000),
719 '4': (
'format_8', 100000),
720 '5': (
'format_8', 10000),
721 '6': (
'format_8', 1000),
722 '7': (
'format_8', 100),
723 '8': (
'format_8', 10),
724 '9': (
'format_9', 1),
725 '10': (
'format_10', 1),
726 '11': (
'format_11', 0),
727 '12': (
'format_13', 0),
728 '13': (
'format_13', 0),
729 '14': (
'format_14', 0),
734 if value ==
'' or value
is None:
736 precision = result.get(self.
namename +
'timePrecision')
737 date_format = WDDateAttribute.DATE_FORMAT.get(precision)
738 if date_format
is not None:
739 format_method = getattr(self, date_format[0])
740 precision = date_format[1]
744 if value.startswith(
'-'):
748 return format_method(value, language)
756 http_response = get(SPARQL_EXPLAIN_URL +
'&' + urlencode({
'query': query}), headers=
get_headers())
758 http_response = post(SPARQL_EXPLAIN_URL, data={
'query': query}, headers=
get_headers())
759 http_response.raise_for_status()
760 return http_response.content
765 for k, v
in WIKIDATA_UNITS.items():
766 WIKIDATA_PROPERTIES[k] = v[
'symbol']
769 wikidata_property_names = []
771 if type(attribute)
in (WDAttribute, WDAmountAttribute, WDURLAttribute, WDDateAttribute, WDLabelAttribute):
772 if attribute.name
not in WIKIDATA_PROPERTIES:
773 wikidata_property_names.append(
"wd:" + attribute.name)
774 query = QUERY_PROPERTY_NAMES.replace(
'%ATTRIBUTES%',
" ".join(wikidata_property_names))
775 jsonresponse = send_wikidata_query(query)
776 for result
in jsonresponse.get(
'results', {}).get(
'bindings', {}):
777 name = result[
'name'][
'value']
778 lang = result[
'name'][
'xml:lang']
779 entity_id = result[
'item'][
'value'].replace(
'http://www.wikidata.org/entity/',
'')
780 WIKIDATA_PROPERTIES[(entity_id, lang)] = name.capitalize()
784 """Uses languages evaluated from :py:obj:`wikipedia.fetch_wikimedia_traits
785 <searx.engines.wikipedia.fetch_wikimedia_traits>` and removes
787 - ``traits.custom['wiki_netloc']``: wikidata does not have net-locations for
788 the languages and the list of all
790 - ``traits.custom['WIKIPEDIA_LANGUAGES']``: not used in the wikipedia engine
794 fetch_wikimedia_traits(engine_traits)
795 engine_traits.custom[
'wiki_netloc'] = {}
796 engine_traits.custom[
'WIKIPEDIA_LANGUAGES'] = []
get_str(self, result, language)
__init__(self, language, kwargs=None)
get_label(self, language)
get_str(self, result, language)
get_str(self, result, language)
get_label(self, language)
format_10(self, value, locale)
get_str(self, result, language)
format_8(self, value, locale)
format_9(self, value, locale)
format_13(self, value, locale)
format_14(self, value, locale)
format_11(self, value, locale)
get_geo_url(self, result, osm_zoom=19)
get_str(self, result, language)
get_label(self, language)
__init__(self, name, url_id=None, priority=100)
get_str(self, result, language)
__init__(self, name, url_id=None, kwargs=None)
get_str(self, result, language)
get_results(attribute_result, attributes, language)
get_query(query, language)
debug_explain_wikidata_query(query, method='GET')
send_wikidata_query(query, method='GET')
fetch_traits(EngineTraits engine_traits)
init(engine_settings=None)
get_label_for_entity(entity_id, language)