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',
76SELECT ?item ?itemLabel ?itemDescription ?lat ?long %SELECT%
79 SERVICE wikibase:mwapi {
80 bd:serviceParam wikibase:endpoint "www.wikidata.org";
81 wikibase:api "EntitySearch";
83 mwapi:search "%QUERY%";
84 mwapi:language "%LANGUAGE%".
85 ?item wikibase:apiOutputItem mwapi:item.
87 hint:Prior hint:runFirst "true".
91 SERVICE wikibase:label {
92 bd:serviceParam wikibase:language "%LANGUAGE%,en".
93 ?item rdfs:label ?itemLabel .
94 ?item schema:description ?itemDescription .
99GROUP BY ?item ?itemLabel ?itemDescription ?lat ?long %GROUP_BY%
103QUERY_PROPERTY_NAMES =
"""
108 WHERE { ?item wdt:P279* wd:Q12132 }
110 VALUES ?item { %ATTRIBUTES% }
112 OPTIONAL { ?item rdfs:label ?name. }
118DUMMY_ENTITY_URLS = set(
119 "http://www.wikidata.org/entity/" + wid
for wid
in (
"Q4115189",
"Q13406268",
"Q15397819",
"Q17339402")
125sparql_string_escape = get_string_replaces_function(
140replace_http_by_https = get_string_replaces_function({
'http:':
'https:'})
145 return {
'Accept':
'application/sparql-results+json',
'User-Agent': searx_useragent()}
149 name = WIKIDATA_PROPERTIES.get(entity_id)
151 name = WIKIDATA_PROPERTIES.get((entity_id, language))
153 name = WIKIDATA_PROPERTIES.get((entity_id, language.split(
'-')[0]))
155 name = WIKIDATA_PROPERTIES.get((entity_id,
'en'))
164 http_response = get(SPARQL_ENDPOINT_URL +
'?' + urlencode({
'query': query}), headers=
get_headers())
167 http_response = post(SPARQL_ENDPOINT_URL, data={
'query': query}, headers=
get_headers())
168 if http_response.status_code != 200:
169 logger.debug(
'SPARQL endpoint error %s', http_response.content.decode())
170 logger.debug(
'request time %s', str(http_response.elapsed))
171 http_response.raise_for_status()
172 return loads(http_response.content.decode())
177 eng_tag, _wiki_netloc = get_wiki_params(params[
'searxng_locale'], traits)
178 query, attributes =
get_query(query, eng_tag)
179 logger.debug(
"request --> language %s // len(attributes): %s", eng_tag, len(attributes))
181 params[
'method'] =
'POST'
182 params[
'url'] = SPARQL_ENDPOINT_URL
183 params[
'data'] = {
'query': query}
185 params[
'language'] = eng_tag
186 params[
'attributes'] = attributes
194 jsonresponse = loads(resp.content.decode())
196 language = resp.search_params[
'language']
197 attributes = resp.search_params[
'attributes']
198 logger.debug(
"request --> language %s // len(attributes): %s", language, len(attributes))
200 seen_entities = set()
201 for result
in jsonresponse.get(
'results', {}).get(
'bindings', []):
202 attribute_result = {key: value[
'value']
for key, value
in result.items()}
203 entity_url = attribute_result[
'item']
204 if entity_url
not in seen_entities
and entity_url
not in DUMMY_ENTITY_URLS:
205 seen_entities.add(entity_url)
206 results +=
get_results(attribute_result, attributes, language)
208 logger.debug(
'The SPARQL request returns duplicate entities: %s', str(attribute_result))
213_IMG_SRC_DEFAULT_URL_PREFIX =
"https://commons.wikimedia.org/wiki/Special:FilePath/"
214_IMG_SRC_NEW_URL_PREFIX =
"https://upload.wikimedia.org/wikipedia/commons/thumb/"
218 """Get Thumbnail image from wikimedia commons
220 Images from commons.wikimedia.org are (HTTP) redirected to
221 upload.wikimedia.org. The redirected URL can be calculated by this
224 - https://stackoverflow.com/a/33691240
227 logger.debug(
'get_thumbnail(): %s', img_src)
228 if not img_src
is None and _IMG_SRC_DEFAULT_URL_PREFIX
in img_src.split()[0]:
229 img_src_name = unquote(img_src.replace(_IMG_SRC_DEFAULT_URL_PREFIX,
"").split(
"?", 1)[0].replace(
"%20",
"_"))
230 img_src_name_first = img_src_name
231 img_src_name_second = img_src_name
233 if ".svg" in img_src_name.split()[0]:
234 img_src_name_second = img_src_name +
".png"
236 img_src_size = img_src.replace(_IMG_SRC_DEFAULT_URL_PREFIX,
"").split(
"?", 1)[1]
237 img_src_size = img_src_size[img_src_size.index(
"=") + 1 : img_src_size.index(
"&")]
238 img_src_name_md5 = md5(img_src_name.encode(
"utf-8")).hexdigest()
240 _IMG_SRC_NEW_URL_PREFIX
241 + img_src_name_md5[0]
243 + img_src_name_md5[0:2]
249 + img_src_name_second
251 logger.debug(
'get_thumbnail() redirected: %s', img_src)
259 infobox_title = attribute_result.get(
'itemLabel')
260 infobox_id = attribute_result[
'item']
261 infobox_id_lang =
None
263 infobox_attributes = []
264 infobox_content = attribute_result.get(
'itemDescription', [])
268 for attribute
in attributes:
269 value = attribute.get_str(attribute_result, language)
270 if value
is not None and value !=
'':
271 attribute_type = type(attribute)
273 if attribute_type
in (WDURLAttribute, WDArticle):
276 for url
in value.split(
', '):
277 infobox_urls.append({
'title': attribute.get_label(language),
'url': url, **attribute.kwargs})
279 if "list" in display_type
and (attribute.kwargs.get(
'official')
or attribute_type == WDArticle):
280 results.append({
'title': infobox_title,
'url': url,
"content": infobox_content})
284 if attribute_type == WDArticle
and (
285 (attribute.language ==
'en' and infobox_id_lang
is None)
or attribute.language !=
'en'
287 infobox_id_lang = attribute.language
289 elif attribute_type == WDImageAttribute:
293 if attribute.priority > img_src_priority:
295 img_src_priority = attribute.priority
296 elif attribute_type == WDGeoAttribute:
301 area = attribute_result.get(
'P2046')
302 osm_zoom = area_to_osm_zoom(area)
if area
else 19
303 url = attribute.get_geo_url(attribute_result, osm_zoom=osm_zoom)
305 infobox_urls.append({
'title': attribute.get_label(language),
'url': url,
'entity': attribute.name})
307 infobox_attributes.append(
308 {
'label': attribute.get_label(language),
'value': value,
'entity': attribute.name}
315 infobox_urls.append({
'title':
'Wikidata',
'url': attribute_result[
'item']})
318 "list" in display_type
320 and len(infobox_attributes) == 0
321 and len(infobox_urls) == 1
322 and len(infobox_content) == 0
324 results.append({
'url': infobox_urls[0][
'url'],
'title': infobox_title,
'content': infobox_content})
325 elif "infobox" in display_type:
328 'infobox': infobox_title,
330 'content': infobox_content,
332 'urls': infobox_urls,
333 'attributes': infobox_attributes,
341 select = [a.get_select()
for a
in attributes]
342 where = list(filter(
lambda s: len(s) > 0, [a.get_where()
for a
in attributes]))
343 wikibase_label = list(filter(
lambda s: len(s) > 0, [a.get_wikibase_label()
for a
in attributes]))
344 group_by = list(filter(
lambda s: len(s) > 0, [a.get_group_by()
for a
in attributes]))
347 .replace(
'%SELECT%',
' '.join(select))
348 .replace(
'%WHERE%',
'\n '.join(where))
349 .replace(
'%WIKIBASE_LABELS%',
'\n '.join(wikibase_label))
350 .replace(
'%GROUP_BY%',
' '.join(group_by))
351 .replace(
'%LANGUAGE%', language)
353 return query, attributes
363 def add_amount(name):
369 def add_url(name, url_id=None, url_path_prefix=None, **kwargs):
370 attributes.append(
WDURLAttribute(name, url_id, url_path_prefix, kwargs))
372 def add_image(name, url_id=None, priority=1):
464 add_url(
'P856', official=
True)
466 if not language.startswith(
'en'):
471 add_url(
'P434', url_id=
'musicbrainz_artist')
472 add_url(
'P435', url_id=
'musicbrainz_work')
473 add_url(
'P436', url_id=
'musicbrainz_release_group')
474 add_url(
'P966', url_id=
'musicbrainz_label')
475 add_url(
'P345', url_id=
'imdb_id')
476 add_url(
'P2397', url_id=
'youtube_channel')
477 add_url(
'P1651', url_id=
'youtube_video')
478 add_url(
'P2002', url_id=
'twitter_profile')
479 add_url(
'P2013', url_id=
'facebook_profile')
480 add_url(
'P2003', url_id=
'instagram_profile')
483 add_url(
'P4033', url_path_prefix=
'/@')
484 add_url(
'P11947', url_path_prefix=
'/c/')
485 add_url(
'P12622', url_path_prefix=
'/c/')
491 add_image(
'P15', priority=1, url_id=
'wikimedia_image')
492 add_image(
'P242', priority=2, url_id=
'wikimedia_image')
493 add_image(
'P154', priority=3, url_id=
'wikimedia_image')
494 add_image(
'P18', priority=4, url_id=
'wikimedia_image')
495 add_image(
'P41', priority=5, url_id=
'wikimedia_image')
496 add_image(
'P2716', priority=6, url_id=
'wikimedia_image')
497 add_image(
'P2910', priority=7, url_id=
'wikimedia_image')
503 __slots__ = (
'name',)
509 return '(group_concat(distinct ?{name};separator=", ") as ?{name}s)'.replace(
'{name}', self.
name)
515 return "OPTIONAL { ?item wdt:{name} ?{name} . }".replace(
'{name}', self.
name)
524 return result.get(self.
name +
's')
527 return '<' + str(type(self).__name__) +
':' + self.
name +
'>'
532 return '?{name} ?{name}Unit'.replace(
'{name}', self.
name)
535 return """ OPTIONAL { ?item p:{name} ?{name}Node .
536 ?{name}Node rdf:type wikibase:BestRank ; ps:{name} ?{name} .
537 OPTIONAL { ?{name}Node psv:{name}/wikibase:quantityUnit ?{name}Unit. } }""".replace(
545 value = result.get(self.
name)
546 unit = result.get(self.
name +
"Unit")
548 unit = unit.replace(
'http://www.wikidata.org/entity/',
'')
555 __slots__ =
'language',
'kwargs'
564 return "Wikipedia ({language})".replace(
'{language}', self.
language)
567 return "?article{language} ?articleName{language}".replace(
'{language}', self.
language)
570 return """OPTIONAL { ?article{language} schema:about ?item ;
571 schema:inLanguage "{language}" ;
572 schema:isPartOf <https://{language}.wikipedia.org/> ;
573 schema:name ?articleName{language} . }""".replace(
581 key =
'article{language}'.replace(
'{language}', self.
language)
582 return result.get(key)
587 return '(group_concat(distinct ?{name}Label;separator=", ") as ?{name}Labels)'.replace(
'{name}', self.
name)
590 return "OPTIONAL { ?item wdt:{name} ?{name} . }".replace(
'{name}', self.
name)
593 return "?{name} rdfs:label ?{name}Label .".replace(
'{name}', self.
name)
596 return result.get(self.
name +
'Labels')
601 HTTP_WIKIMEDIA_IMAGE =
'http://commons.wikimedia.org/wiki/Special:FilePath/'
603 __slots__ =
'url_id',
'url_path_prefix',
'kwargs'
605 def __init__(self, name, url_id=None, url_path_prefix=None, kwargs=None):
607 :param url_id: ID matching one key in ``external_urls.json`` for
608 converting IDs to full URLs.
610 :param url_path_prefix: Path prefix if the values are of format
611 ``account@domain``. If provided, value are rewritten to
612 ``https://<domain><url_path_prefix><account>``. For example::
614 WDURLAttribute('P4033', url_path_prefix='/@')
616 Adds Property `P4033 <https://www.wikidata.org/wiki/Property:P4033>`_
617 to the wikidata query. This field might return for example
618 ``libreoffice@fosstodon.org`` and the URL built from this is then:
620 - account: ``libreoffice``
621 - domain: ``fosstodon.org``
622 - result url: https://fosstodon.org/@libreoffice
631 value = result.get(self.
name +
's')
635 value = value.split(
',')[0]
638 if value.startswith(WDURLAttribute.HTTP_WIKIMEDIA_IMAGE):
639 value = value[len(WDURLAttribute.HTTP_WIKIMEDIA_IMAGE) :]
640 url_id =
'wikimedia_image'
641 return get_external_url(url_id, value)
644 [account, domain] = value.split(
'@', 1)
645 return f
"https://{domain}{self.url_path_prefix}{account}"
652 return "OpenStreetMap"
655 return "?{name}Lat ?{name}Long".replace(
'{name}', self.
name)
658 return """OPTIONAL { ?item p:{name}/psv:{name} [
659 wikibase:geoLatitude ?{name}Lat ;
660 wikibase:geoLongitude ?{name}Long ] }""".replace(
668 latitude = result.get(self.
name +
'Lat')
669 longitude = result.get(self.
name +
'Long')
670 if latitude
and longitude:
671 return latitude +
' ' + longitude
675 latitude = result.get(self.
name +
'Lat')
676 longitude = result.get(self.
name +
'Long')
677 if latitude
and longitude:
678 return get_earth_coordinates_url(latitude, longitude, osm_zoom)
684 __slots__ = (
'priority',)
686 def __init__(self, name, url_id=None, priority=100):
693 return '?{name} ?{name}timePrecision ?{name}timeZone ?{name}timeCalendar'.replace(
'{name}', self.
name)
700 return """OPTIONAL { ?item p:{name}/psv:{name} [
701 wikibase:timeValue ?{name} ;
702 wikibase:timePrecision ?{name}timePrecision ;
703 wikibase:timeTimezone ?{name}timeZone ;
704 wikibase:timeCalendarModel ?{name}timeCalendar ] . }
705 hint:Prior hint:rangeSafe true;""".replace(
723 timestamp = isoparse(value)
724 return format_date(timestamp, format=
'yyyy', locale=locale)
728 timestamp = isoparse(value)
729 return format_date(timestamp, format=
'MMMM y', locale=locale)
733 timestamp = isoparse(value)
734 return format_date(timestamp, format=
'full', locale=locale)
737 timestamp = isoparse(value)
740 get_datetime_format(format, locale=locale)
742 .replace(
'{0}', format_time(timestamp,
'full', tzinfo=
None, locale=locale))
743 .replace(
'{1}', format_date(timestamp,
'short', locale=locale))
748 return format_datetime(isoparse(value), format=
'full', locale=locale)
751 '0': (
'format_8', 1000000000),
752 '1': (
'format_8', 100000000),
753 '2': (
'format_8', 10000000),
754 '3': (
'format_8', 1000000),
755 '4': (
'format_8', 100000),
756 '5': (
'format_8', 10000),
757 '6': (
'format_8', 1000),
758 '7': (
'format_8', 100),
759 '8': (
'format_8', 10),
760 '9': (
'format_9', 1),
761 '10': (
'format_10', 1),
762 '11': (
'format_11', 0),
763 '12': (
'format_13', 0),
764 '13': (
'format_13', 0),
765 '14': (
'format_14', 0),
769 value = result.get(self.
name)
770 if value ==
'' or value
is None:
772 precision = result.get(self.
name +
'timePrecision')
773 date_format = WDDateAttribute.DATE_FORMAT.get(precision)
774 if date_format
is not None:
775 format_method = getattr(self, date_format[0])
776 precision = date_format[1]
780 if value.startswith(
'-'):
784 return format_method(value, language)
792 http_response = get(SPARQL_EXPLAIN_URL +
'&' + urlencode({
'query': query}), headers=
get_headers())
794 http_response = post(SPARQL_EXPLAIN_URL, data={
'query': query}, headers=
get_headers())
795 http_response.raise_for_status()
796 return http_response.content
801 for k, v
in WIKIDATA_UNITS.items():
802 WIKIDATA_PROPERTIES[k] = v[
'symbol']
805 wikidata_property_names = []
807 if type(attribute)
in (WDAttribute, WDAmountAttribute, WDURLAttribute, WDDateAttribute, WDLabelAttribute):
808 if attribute.name
not in WIKIDATA_PROPERTIES:
809 wikidata_property_names.append(
"wd:" + attribute.name)
810 query = QUERY_PROPERTY_NAMES.replace(
'%ATTRIBUTES%',
" ".join(wikidata_property_names))
812 for result
in jsonresponse.get(
'results', {}).get(
'bindings', {}):
813 name = result[
'name'][
'value']
814 lang = result[
'name'][
'xml:lang']
815 entity_id = result[
'item'][
'value'].replace(
'http://www.wikidata.org/entity/',
'')
816 WIKIDATA_PROPERTIES[(entity_id, lang)] = name.capitalize()
820 """Uses languages evaluated from :py:obj:`wikipedia.fetch_wikimedia_traits
821 <searx.engines.wikipedia.fetch_wikimedia_traits>` and removes
823 - ``traits.custom['wiki_netloc']``: wikidata does not have net-locations for
824 the languages and the list of all
826 - ``traits.custom['WIKIPEDIA_LANGUAGES']``: not used in the wikipedia engine
830 fetch_wikimedia_traits(engine_traits)
831 engine_traits.custom[
'wiki_netloc'] = {}
832 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, url_path_prefix=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)