.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
wikidata.py
Go to the documentation of this file.
1# SPDX-License-Identifier: AGPL-3.0-or-later
2"""This module implements the Wikidata engine. Some implementations are shared
3from :ref:`wikipedia engine`.
4
5"""
6# pylint: disable=missing-class-docstring
7
8from typing import TYPE_CHECKING
9from hashlib import md5
10from urllib.parse import urlencode, unquote
11from json import loads
12
13from dateutil.parser import isoparse
14from babel.dates import format_datetime, format_date, format_time, get_datetime_format
15
16from searx.data import WIKIDATA_UNITS
17from searx.network import post, get
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
20from searx.engines.wikipedia import (
21 fetch_wikimedia_traits,
22 get_wiki_params,
23)
24from searx.enginelib.traits import EngineTraits
25
26if TYPE_CHECKING:
27 import logging
28
29 logger: logging.Logger
30
31traits: EngineTraits
32
33# about
34about = {
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,
40 "results": 'JSON',
41}
42
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."""
47
48
49# SPARQL
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',
57 'P345': 'IMDb',
58 'P2397': 'YouTube',
59 'P1651': 'YouTube',
60 'P2002': 'Twitter',
61 'P2013': 'Facebook',
62 'P2003': 'Instagram',
63}
64
65# SERVICE wikibase:mwapi : https://www.mediawiki.org/wiki/Wikidata_Query_Service/User_Manual/MWAPI
66# SERVICE wikibase:label: https://en.wikibooks.org/wiki/SPARQL/SERVICE_-_Label#Manual_Label_SERVICE
67# https://en.wikibooks.org/wiki/SPARQL/WIKIDATA_Precision,_Units_and_Coordinates
68# https://www.mediawiki.org/wiki/Wikibase/Indexing/RDF_Dump_Format#Data_model
69# optimization:
70# * https://www.wikidata.org/wiki/Wikidata:SPARQL_query_service/query_optimization
71# * https://github.com/blazegraph/database/wiki/QueryHints
72QUERY_TEMPLATE = """
73SELECT ?item ?itemLabel ?itemDescription ?lat ?long %SELECT%
74WHERE
75{
76 SERVICE wikibase:mwapi {
77 bd:serviceParam wikibase:endpoint "www.wikidata.org";
78 wikibase:api "EntitySearch";
79 wikibase:limit 1;
80 mwapi:search "%QUERY%";
81 mwapi:language "%LANGUAGE%".
82 ?item wikibase:apiOutputItem mwapi:item.
83 }
84 hint:Prior hint:runFirst "true".
85
86 %WHERE%
87
88 SERVICE wikibase:label {
89 bd:serviceParam wikibase:language "%LANGUAGE%,en".
90 ?item rdfs:label ?itemLabel .
91 ?item schema:description ?itemDescription .
92 %WIKIBASE_LABELS%
93 }
94
95}
96GROUP BY ?item ?itemLabel ?itemDescription ?lat ?long %GROUP_BY%
97"""
98
99# Get the calendar names and the property names
100QUERY_PROPERTY_NAMES = """
101SELECT ?item ?name
102WHERE {
103 {
104 SELECT ?item
105 WHERE { ?item wdt:P279* wd:Q12132 }
106 } UNION {
107 VALUES ?item { %ATTRIBUTES% }
108 }
109 OPTIONAL { ?item rdfs:label ?name. }
110}
111"""
112
113# see the property "dummy value" of https://www.wikidata.org/wiki/Q2013 (Wikidata)
114# hard coded here to avoid to an additional SPARQL request when the server starts
115DUMMY_ENTITY_URLS = set(
116 "http://www.wikidata.org/entity/" + wid for wid in ("Q4115189", "Q13406268", "Q15397819", "Q17339402")
117)
118
119
120# https://www.w3.org/TR/sparql11-query/#rSTRING_LITERAL1
121# https://lists.w3.org/Archives/Public/public-rdf-dawg/2011OctDec/0175.html
122sparql_string_escape = get_string_replaces_function(
123 # fmt: off
124 {
125 '\t': '\\\t',
126 '\n': '\\\n',
127 '\r': '\\\r',
128 '\b': '\\\b',
129 '\f': '\\\f',
130 '\"': '\\\"',
131 '\'': '\\\'',
132 '\\': '\\\\'
133 }
134 # fmt: on
135)
136
137replace_http_by_https = get_string_replaces_function({'http:': 'https:'})
138
139
141 # user agent: https://www.mediawiki.org/wiki/Wikidata_Query_Service/User_Manual#Query_limits
142 return {'Accept': 'application/sparql-results+json', 'User-Agent': searx_useragent()}
143
144
145def get_label_for_entity(entity_id, language):
146 name = WIKIDATA_PROPERTIES.get(entity_id)
147 if name is None:
148 name = WIKIDATA_PROPERTIES.get((entity_id, language))
149 if name is None:
150 name = WIKIDATA_PROPERTIES.get((entity_id, language.split('-')[0]))
151 if name is None:
152 name = WIKIDATA_PROPERTIES.get((entity_id, 'en'))
153 if name is None:
154 name = entity_id
155 return name
156
157
158def send_wikidata_query(query, method='GET'):
159 if method == 'GET':
160 # query will be cached by wikidata
161 http_response = get(SPARQL_ENDPOINT_URL + '?' + urlencode({'query': query}), headers=get_headers())
162 else:
163 # query won't be cached by wikidata
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())
170
171
172def request(query, params):
173
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))
177
178 params['method'] = 'POST'
179 params['url'] = SPARQL_ENDPOINT_URL
180 params['data'] = {'query': query}
181 params['headers'] = get_headers()
182 params['language'] = eng_tag
183 params['attributes'] = attributes
184
185 return params
186
187
188def response(resp):
189
190 results = []
191 jsonresponse = loads(resp.content.decode())
192
193 language = resp.search_params['language']
194 attributes = resp.search_params['attributes']
195 logger.debug("request --> language %s // len(attributes): %s", language, len(attributes))
196
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)
204 else:
205 logger.debug('The SPARQL request returns duplicate entities: %s', str(attribute_result))
206
207 return results
208
209
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/"
212
213
214def get_thumbnail(img_src):
215 """Get Thumbnail image from wikimedia commons
216
217 Images from commons.wikimedia.org are (HTTP) redirected to
218 upload.wikimedia.org. The redirected URL can be calculated by this
219 function.
220
221 - https://stackoverflow.com/a/33691240
222
223 """
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
229
230 if ".svg" in img_src_name.split()[0]:
231 img_src_name_second = img_src_name + ".png"
232
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()
236 img_src = (
237 _IMG_SRC_NEW_URL_PREFIX
238 + img_src_name_md5[0]
239 + "/"
240 + img_src_name_md5[0:2]
241 + "/"
242 + img_src_name_first
243 + "/"
244 + img_src_size
245 + "px-"
246 + img_src_name_second
247 )
248 logger.debug('get_thumbnail() redirected: %s', img_src)
249
250 return img_src
251
252
253def get_results(attribute_result, attributes, language):
254 # pylint: disable=too-many-branches
255 results = []
256 infobox_title = attribute_result.get('itemLabel')
257 infobox_id = attribute_result['item']
258 infobox_id_lang = None
259 infobox_urls = []
260 infobox_attributes = []
261 infobox_content = attribute_result.get('itemDescription', [])
262 img_src = None
263 img_src_priority = 0
264
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)
269
270 if attribute_type in (WDURLAttribute, WDArticle):
271 # get_select() method : there is group_concat(distinct ...;separator=", ")
272 # split the value here
273 for url in value.split(', '):
274 infobox_urls.append({'title': attribute.get_label(language), 'url': url, **attribute.kwargs})
275 # "normal" results (not infobox) include official website and Wikipedia links.
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})
278
279 # update the infobox_id with the wikipedia URL
280 # first the local wikipedia URL, and as fallback the english wikipedia URL
281 if attribute_type == WDArticle and (
282 (attribute.language == 'en' and infobox_id_lang is None) or attribute.language != 'en'
283 ):
284 infobox_id_lang = attribute.language
285 infobox_id = url
286 elif attribute_type == WDImageAttribute:
287 # this attribute is an image.
288 # replace the current image only the priority is lower
289 # (the infobox contain only one image).
290 if attribute.priority > img_src_priority:
291 img_src = get_thumbnail(value)
292 img_src_priority = attribute.priority
293 elif attribute_type == WDGeoAttribute:
294 # geocoordinate link
295 # use the area to get the OSM zoom
296 # Note: ignore the unit (must be kmĀ² otherwise the calculation is wrong)
297 # Should use normalized value p:P2046/psn:P2046/wikibase:quantityAmount
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)
301 if url:
302 infobox_urls.append({'title': attribute.get_label(language), 'url': url, 'entity': attribute.name})
303 else:
304 infobox_attributes.append(
305 {'label': attribute.get_label(language), 'value': value, 'entity': attribute.name}
306 )
307
308 if infobox_id:
309 infobox_id = replace_http_by_https(infobox_id)
310
311 # add the wikidata URL at the end
312 infobox_urls.append({'title': 'Wikidata', 'url': attribute_result['item']})
313
314 if (
315 "list" in display_type
316 and img_src is None
317 and len(infobox_attributes) == 0
318 and len(infobox_urls) == 1
319 and len(infobox_content) == 0
320 ):
321 results.append({'url': infobox_urls[0]['url'], 'title': infobox_title, 'content': infobox_content})
322 elif "infobox" in display_type:
323 results.append(
324 {
325 'infobox': infobox_title,
326 'id': infobox_id,
327 'content': infobox_content,
328 'img_src': img_src,
329 'urls': infobox_urls,
330 'attributes': infobox_attributes,
331 }
332 )
333 return results
334
335
336def get_query(query, language):
337 attributes = get_attributes(language)
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]))
342 query = (
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)
349 )
350 return query, attributes
351
352
353def get_attributes(language):
354 # pylint: disable=too-many-statements
355 attributes = []
356
357 def add_value(name):
358 attributes.append(WDAttribute(name))
359
360 def add_amount(name):
361 attributes.append(WDAmountAttribute(name))
362
363 def add_label(name):
364 attributes.append(WDLabelAttribute(name))
365
366 def add_url(name, url_id=None, **kwargs):
367 attributes.append(WDURLAttribute(name, url_id, kwargs))
368
369 def add_image(name, url_id=None, priority=1):
370 attributes.append(WDImageAttribute(name, url_id, priority))
371
372 def add_date(name):
373 attributes.append(WDDateAttribute(name))
374
375 # Dates
376 for p in [
377 'P571', # inception date
378 'P576', # dissolution date
379 'P580', # start date
380 'P582', # end date
381 'P569', # date of birth
382 'P570', # date of death
383 'P619', # date of spacecraft launch
384 'P620',
385 ]: # date of spacecraft landing
386 add_date(p)
387
388 for p in [
389 'P27', # country of citizenship
390 'P495', # country of origin
391 'P17', # country
392 'P159',
393 ]: # headquarters location
394 add_label(p)
395
396 # Places
397 for p in [
398 'P36', # capital
399 'P35', # head of state
400 'P6', # head of government
401 'P122', # basic form of government
402 'P37',
403 ]: # official language
404 add_label(p)
405
406 add_value('P1082') # population
407 add_amount('P2046') # area
408 add_amount('P281') # postal code
409 add_label('P38') # currency
410 add_amount('P2048') # height (building)
411
412 # Media
413 for p in [
414 'P400', # platform (videogames, computing)
415 'P50', # author
416 'P170', # creator
417 'P57', # director
418 'P175', # performer
419 'P178', # developer
420 'P162', # producer
421 'P176', # manufacturer
422 'P58', # screenwriter
423 'P272', # production company
424 'P264', # record label
425 'P123', # publisher
426 'P449', # original network
427 'P750', # distributed by
428 'P86',
429 ]: # composer
430 add_label(p)
431
432 add_date('P577') # publication date
433 add_label('P136') # genre (music, film, artistic...)
434 add_label('P364') # original language
435 add_value('P212') # ISBN-13
436 add_value('P957') # ISBN-10
437 add_label('P275') # copyright license
438 add_label('P277') # programming language
439 add_value('P348') # version
440 add_label('P840') # narrative location
441
442 # Languages
443 add_value('P1098') # number of speakers
444 add_label('P282') # writing system
445 add_label('P1018') # language regulatory body
446 add_value('P218') # language code (ISO 639-1)
447
448 # Other
449 add_label('P169') # ceo
450 add_label('P112') # founded by
451 add_label('P1454') # legal form (company, organization)
452 add_label('P137') # operator (service, facility, ...)
453 add_label('P1029') # crew members (tripulation)
454 add_label('P225') # taxon name
455 add_value('P274') # chemical formula
456 add_label('P1346') # winner (sports, contests, ...)
457 add_value('P1120') # number of deaths
458 add_value('P498') # currency code (ISO 4217)
459
460 # URL
461 add_url('P856', official=True) # official website
462 attributes.append(WDArticle(language)) # wikipedia (user language)
463 if not language.startswith('en'):
464 attributes.append(WDArticle('en')) # wikipedia (english)
465
466 add_url('P1324') # source code repository
467 add_url('P1581') # blog
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')
478
479 # Map
480 attributes.append(WDGeoAttribute('P625'))
481
482 # Image
483 add_image('P15', priority=1, url_id='wikimedia_image') # route map
484 add_image('P242', priority=2, url_id='wikimedia_image') # locator map
485 add_image('P154', priority=3, url_id='wikimedia_image') # logo
486 add_image('P18', priority=4, url_id='wikimedia_image') # image
487 add_image('P41', priority=5, url_id='wikimedia_image') # flag
488 add_image('P2716', priority=6, url_id='wikimedia_image') # collage
489 add_image('P2910', priority=7, url_id='wikimedia_image') # icon
490
491 return attributes
492
493
495 __slots__ = ('name',)
496
497 def __init__(self, name):
498 self.name = name
499
500 def get_select(self):
501 return '(group_concat(distinct ?{name};separator=", ") as ?{name}s)'.replace('{name}', self.name)
502
503 def get_label(self, language):
504 return get_label_for_entity(self.name, language)
505
506 def get_where(self):
507 return "OPTIONAL { ?item wdt:{name} ?{name} . }".replace('{name}', self.name)
508
510 return ""
511
512 def get_group_by(self):
513 return ""
514
515 def get_str(self, result, language): # pylint: disable=unused-argument
516 return result.get(self.name + 's')
517
518 def __repr__(self):
519 return '<' + str(type(self).__name__) + ':' + self.name + '>'
520
521
523 def get_select(self):
524 return '?{name} ?{name}Unit'.replace('{name}', self.namename)
525
526 def get_where(self):
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(
530 '{name}', self.namename
531 )
532
533 def get_group_by(self):
534 return self.get_selectget_select()
535
536 def get_str(self, result, language):
537 value = result.get(self.namename)
538 unit = result.get(self.namename + "Unit")
539 if unit is not None:
540 unit = unit.replace('http://www.wikidata.org/entity/', '')
541 return value + " " + get_label_for_entity(unit, language)
542 return value
543
544
546
547 __slots__ = 'language', 'kwargs'
548
549 def __init__(self, language, kwargs=None):
550 super().__init__('wikipedia')
551 self.language = language
552 self.kwargs = kwargs or {}
553
554 def get_label(self, language):
555 # language parameter is ignored
556 return "Wikipedia ({language})".replace('{language}', self.language)
557
558 def get_select(self):
559 return "?article{language} ?articleName{language}".replace('{language}', self.language)
560
561 def get_where(self):
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(
566 '{language}', self.language
567 )
568
569 def get_group_by(self):
570 return self.get_selectget_select()
571
572 def get_str(self, result, language):
573 key = 'article{language}'.replace('{language}', self.language)
574 return result.get(key)
575
576
578 def get_select(self):
579 return '(group_concat(distinct ?{name}Label;separator=", ") as ?{name}Labels)'.replace('{name}', self.namename)
580
581 def get_where(self):
582 return "OPTIONAL { ?item wdt:{name} ?{name} . }".replace('{name}', self.namename)
583
585 return "?{name} rdfs:label ?{name}Label .".replace('{name}', self.namename)
586
587 def get_str(self, result, language):
588 return result.get(self.namename + 'Labels')
589
590
592
593 HTTP_WIKIMEDIA_IMAGE = 'http://commons.wikimedia.org/wiki/Special:FilePath/'
594
595 __slots__ = 'url_id', 'kwargs'
596
597 def __init__(self, name, url_id=None, kwargs=None):
598 super().__init__(name)
599 self.url_id = url_id
600 self.kwargs = kwargs
601
602 def get_str(self, result, language):
603 value = result.get(self.name + 's')
604 if self.url_id and value is not None and value != '':
605 value = value.split(',')[0]
606 url_id = self.url_id
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)
611 return value
612
613
615 def get_label(self, language):
616 return "OpenStreetMap"
617
618 def get_select(self):
619 return "?{name}Lat ?{name}Long".replace('{name}', self.namename)
620
621 def get_where(self):
622 return """OPTIONAL { ?item p:{name}/psv:{name} [
623 wikibase:geoLatitude ?{name}Lat ;
624 wikibase:geoLongitude ?{name}Long ] }""".replace(
625 '{name}', self.namename
626 )
627
628 def get_group_by(self):
629 return self.get_selectget_select()
630
631 def get_str(self, result, language):
632 latitude = result.get(self.namename + 'Lat')
633 longitude = result.get(self.namename + 'Long')
634 if latitude and longitude:
635 return latitude + ' ' + longitude
636 return None
637
638 def get_geo_url(self, result, osm_zoom=19):
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)
643 return None
644
645
647
648 __slots__ = ('priority',)
649
650 def __init__(self, name, url_id=None, priority=100):
651 super().__init__(name, url_id)
652 self.priority = priority
653
654
656 def get_select(self):
657 return '?{name} ?{name}timePrecision ?{name}timeZone ?{name}timeCalendar'.replace('{name}', self.namename)
658
659 def get_where(self):
660 # To remove duplicate, add
661 # FILTER NOT EXISTS { ?item p:{name}/psv:{name}/wikibase:timeValue ?{name}bis FILTER (?{name}bis < ?{name}) }
662 # this filter is too slow, so the response function ignore duplicate results
663 # (see the seen_entities variable)
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(
670 '{name}', self.namename
671 )
672
673 def get_group_by(self):
674 return self.get_selectget_select()
675
676 def format_8(self, value, locale): # pylint: disable=unused-argument
677 # precision: less than a year
678 return value
679
680 def format_9(self, value, locale):
681 year = int(value)
682 # precision: year
683 if year < 1584:
684 if year < 0:
685 return str(year - 1)
686 return str(year)
687 timestamp = isoparse(value)
688 return format_date(timestamp, format='yyyy', locale=locale)
689
690 def format_10(self, value, locale):
691 # precision: month
692 timestamp = isoparse(value)
693 return format_date(timestamp, format='MMMM y', locale=locale)
694
695 def format_11(self, value, locale):
696 # precision: day
697 timestamp = isoparse(value)
698 return format_date(timestamp, format='full', locale=locale)
699
700 def format_13(self, value, locale):
701 timestamp = isoparse(value)
702 # precision: minute
703 return (
704 get_datetime_format(format, locale=locale)
705 .replace("'", "")
706 .replace('{0}', format_time(timestamp, 'full', tzinfo=None, locale=locale))
707 .replace('{1}', format_date(timestamp, 'short', locale=locale))
708 )
709
710 def format_14(self, value, locale):
711 # precision: second.
712 return format_datetime(isoparse(value), format='full', locale=locale)
713
714 DATE_FORMAT = {
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), # year
725 '10': ('format_10', 1), # month
726 '11': ('format_11', 0), # day
727 '12': ('format_13', 0), # hour (not supported by babel, display minute)
728 '13': ('format_13', 0), # minute
729 '14': ('format_14', 0), # second
730 }
731
732 def get_str(self, result, language):
733 value = result.get(self.namename)
734 if value == '' or value is None:
735 return 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]
741 try:
742 if precision >= 1:
743 t = value.split('-')
744 if value.startswith('-'):
745 value = '-' + t[1]
746 else:
747 value = t[0]
748 return format_method(value, language)
749 except Exception: # pylint: disable=broad-except
750 return value
751 return value
752
753
754def debug_explain_wikidata_query(query, method='GET'):
755 if method == 'GET':
756 http_response = get(SPARQL_EXPLAIN_URL + '&' + urlencode({'query': query}), headers=get_headers())
757 else:
758 http_response = post(SPARQL_EXPLAIN_URL, data={'query': query}, headers=get_headers())
759 http_response.raise_for_status()
760 return http_response.content
761
762
763def init(engine_settings=None): # pylint: disable=unused-argument
764 # WIKIDATA_PROPERTIES : add unit symbols
765 for k, v in WIKIDATA_UNITS.items():
766 WIKIDATA_PROPERTIES[k] = v['symbol']
767
768 # WIKIDATA_PROPERTIES : add property labels
769 wikidata_property_names = []
770 for attribute in get_attributes('en'):
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()
781
782
783def fetch_traits(engine_traits: EngineTraits):
784 """Uses languages evaluated from :py:obj:`wikipedia.fetch_wikimedia_traits
785 <searx.engines.wikipedia.fetch_wikimedia_traits>` and removes
786
787 - ``traits.custom['wiki_netloc']``: wikidata does not have net-locations for
788 the languages and the list of all
789
790 - ``traits.custom['WIKIPEDIA_LANGUAGES']``: not used in the wikipedia engine
791
792 """
793
794 fetch_wikimedia_traits(engine_traits)
795 engine_traits.custom['wiki_netloc'] = {}
796 engine_traits.custom['WIKIPEDIA_LANGUAGES'] = []
get_str(self, result, language)
Definition wikidata.py:536
__init__(self, language, kwargs=None)
Definition wikidata.py:549
get_str(self, result, language)
Definition wikidata.py:572
get_str(self, result, language)
Definition wikidata.py:515
get_str(self, result, language)
Definition wikidata.py:732
get_geo_url(self, result, osm_zoom=19)
Definition wikidata.py:638
get_str(self, result, language)
Definition wikidata.py:631
__init__(self, name, url_id=None, priority=100)
Definition wikidata.py:650
get_str(self, result, language)
Definition wikidata.py:587
__init__(self, name, url_id=None, kwargs=None)
Definition wikidata.py:597
get_str(self, result, language)
Definition wikidata.py:602
request(query, params)
Definition wikidata.py:172
get_results(attribute_result, attributes, language)
Definition wikidata.py:253
get_query(query, language)
Definition wikidata.py:336
debug_explain_wikidata_query(query, method='GET')
Definition wikidata.py:754
send_wikidata_query(query, method='GET')
Definition wikidata.py:158
get_attributes(language)
Definition wikidata.py:353
fetch_traits(EngineTraits engine_traits)
Definition wikidata.py:783
init(engine_settings=None)
Definition wikidata.py:763
get_label_for_entity(entity_id, language)
Definition wikidata.py:145