wikidata.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """
  3. Wikidata
  4. """
  5. from urllib.parse import urlencode
  6. from json import loads
  7. from dateutil.parser import isoparse
  8. from babel.dates import format_datetime, format_date, format_time, get_datetime_format
  9. from searx.data import WIKIDATA_UNITS
  10. from searx.network import post, get
  11. from searx.utils import match_language, searx_useragent, get_string_replaces_function
  12. from searx.external_urls import get_external_url, get_earth_coordinates_url, area_to_osm_zoom
  13. from searx.engines.wikipedia import ( # pylint: disable=unused-import
  14. _fetch_supported_languages,
  15. supported_languages_url,
  16. )
  17. # about
  18. about = {
  19. "website": 'https://wikidata.org/',
  20. "wikidata_id": 'Q2013',
  21. "official_api_documentation": 'https://query.wikidata.org/',
  22. "use_official_api": True,
  23. "require_api_key": False,
  24. "results": 'JSON',
  25. }
  26. # SPARQL
  27. SPARQL_ENDPOINT_URL = 'https://query.wikidata.org/sparql'
  28. SPARQL_EXPLAIN_URL = 'https://query.wikidata.org/bigdata/namespace/wdq/sparql?explain'
  29. WIKIDATA_PROPERTIES = {
  30. 'P434': 'MusicBrainz',
  31. 'P435': 'MusicBrainz',
  32. 'P436': 'MusicBrainz',
  33. 'P966': 'MusicBrainz',
  34. 'P345': 'IMDb',
  35. 'P2397': 'YouTube',
  36. 'P1651': 'YouTube',
  37. 'P2002': 'Twitter',
  38. 'P2013': 'Facebook',
  39. 'P2003': 'Instagram',
  40. }
  41. # SERVICE wikibase:mwapi : https://www.mediawiki.org/wiki/Wikidata_Query_Service/User_Manual/MWAPI
  42. # SERVICE wikibase:label: https://en.wikibooks.org/wiki/SPARQL/SERVICE_-_Label#Manual_Label_SERVICE
  43. # https://en.wikibooks.org/wiki/SPARQL/WIKIDATA_Precision,_Units_and_Coordinates
  44. # https://www.mediawiki.org/wiki/Wikibase/Indexing/RDF_Dump_Format#Data_model
  45. # optmization:
  46. # * https://www.wikidata.org/wiki/Wikidata:SPARQL_query_service/query_optimization
  47. # * https://github.com/blazegraph/database/wiki/QueryHints
  48. QUERY_TEMPLATE = """
  49. SELECT ?item ?itemLabel ?itemDescription ?lat ?long %SELECT%
  50. WHERE
  51. {
  52. SERVICE wikibase:mwapi {
  53. bd:serviceParam wikibase:endpoint "www.wikidata.org";
  54. wikibase:api "EntitySearch";
  55. wikibase:limit 1;
  56. mwapi:search "%QUERY%";
  57. mwapi:language "%LANGUAGE%".
  58. ?item wikibase:apiOutputItem mwapi:item.
  59. }
  60. %WHERE%
  61. SERVICE wikibase:label {
  62. bd:serviceParam wikibase:language "%LANGUAGE%,en".
  63. ?item rdfs:label ?itemLabel .
  64. ?item schema:description ?itemDescription .
  65. %WIKIBASE_LABELS%
  66. }
  67. }
  68. GROUP BY ?item ?itemLabel ?itemDescription ?lat ?long %GROUP_BY%
  69. """
  70. # Get the calendar names and the property names
  71. QUERY_PROPERTY_NAMES = """
  72. SELECT ?item ?name
  73. WHERE {
  74. {
  75. SELECT ?item
  76. WHERE { ?item wdt:P279* wd:Q12132 }
  77. } UNION {
  78. VALUES ?item { %ATTRIBUTES% }
  79. }
  80. OPTIONAL { ?item rdfs:label ?name. }
  81. }
  82. """
  83. # https://www.w3.org/TR/sparql11-query/#rSTRING_LITERAL1
  84. # https://lists.w3.org/Archives/Public/public-rdf-dawg/2011OctDec/0175.html
  85. sparql_string_escape = get_string_replaces_function(
  86. # fmt: off
  87. {
  88. '\t': '\\\t',
  89. '\n': '\\\n',
  90. '\r': '\\\r',
  91. '\b': '\\\b',
  92. '\f': '\\\f',
  93. '\"': '\\\"',
  94. '\'': '\\\'',
  95. '\\': '\\\\'
  96. }
  97. # fmt: on
  98. )
  99. replace_http_by_https = get_string_replaces_function({'http:': 'https:'})
  100. def get_headers():
  101. # user agent: https://www.mediawiki.org/wiki/Wikidata_Query_Service/User_Manual#Query_limits
  102. return {'Accept': 'application/sparql-results+json', 'User-Agent': searx_useragent()}
  103. def get_label_for_entity(entity_id, language):
  104. name = WIKIDATA_PROPERTIES.get(entity_id)
  105. if name is None:
  106. name = WIKIDATA_PROPERTIES.get((entity_id, language))
  107. if name is None:
  108. name = WIKIDATA_PROPERTIES.get((entity_id, language.split('-')[0]))
  109. if name is None:
  110. name = WIKIDATA_PROPERTIES.get((entity_id, 'en'))
  111. if name is None:
  112. name = entity_id
  113. return name
  114. def send_wikidata_query(query, method='GET'):
  115. if method == 'GET':
  116. # query will be cached by wikidata
  117. http_response = get(SPARQL_ENDPOINT_URL + '?' + urlencode({'query': query}), headers=get_headers())
  118. else:
  119. # query won't be cached by wikidata
  120. http_response = post(SPARQL_ENDPOINT_URL, data={'query': query}, headers=get_headers())
  121. if http_response.status_code != 200:
  122. logger.debug('SPARQL endpoint error %s', http_response.content.decode())
  123. logger.debug('request time %s', str(http_response.elapsed))
  124. http_response.raise_for_status()
  125. return loads(http_response.content.decode())
  126. def request(query, params):
  127. language = params['language'].split('-')[0]
  128. if language == 'all':
  129. language = 'en'
  130. else:
  131. language = match_language(params['language'], supported_languages, language_aliases).split('-')[0]
  132. query, attributes = get_query(query, language)
  133. params['method'] = 'POST'
  134. params['url'] = SPARQL_ENDPOINT_URL
  135. params['data'] = {'query': query}
  136. params['headers'] = get_headers()
  137. params['language'] = language
  138. params['attributes'] = attributes
  139. return params
  140. def response(resp):
  141. results = []
  142. jsonresponse = loads(resp.content.decode())
  143. language = resp.search_params['language'].lower()
  144. attributes = resp.search_params['attributes']
  145. seen_entities = set()
  146. for result in jsonresponse.get('results', {}).get('bindings', []):
  147. attribute_result = {key: value['value'] for key, value in result.items()}
  148. entity_url = attribute_result['item']
  149. if entity_url not in seen_entities:
  150. seen_entities.add(entity_url)
  151. results += get_results(attribute_result, attributes, language)
  152. else:
  153. logger.debug('The SPARQL request returns duplicate entities: %s', str(attribute_result))
  154. return results
  155. def get_results(attribute_result, attributes, language):
  156. results = []
  157. infobox_title = attribute_result.get('itemLabel')
  158. infobox_id = attribute_result['item']
  159. infobox_id_lang = None
  160. infobox_urls = []
  161. infobox_attributes = []
  162. infobox_content = attribute_result.get('itemDescription', [])
  163. img_src = None
  164. img_src_priority = 100
  165. for attribute in attributes:
  166. value = attribute.get_str(attribute_result, language)
  167. if value is not None and value != '':
  168. attribute_type = type(attribute)
  169. if attribute_type in (WDURLAttribute, WDArticle):
  170. # get_select() method : there is group_concat(distinct ...;separator=", ")
  171. # split the value here
  172. for url in value.split(', '):
  173. infobox_urls.append({'title': attribute.get_label(language), 'url': url, **attribute.kwargs})
  174. # "normal" results (not infobox) include official website and Wikipedia links.
  175. if attribute.kwargs.get('official') or attribute_type == WDArticle:
  176. results.append({'title': infobox_title, 'url': url})
  177. # update the infobox_id with the wikipedia URL
  178. # first the local wikipedia URL, and as fallback the english wikipedia URL
  179. if attribute_type == WDArticle and (
  180. (attribute.language == 'en' and infobox_id_lang is None) or attribute.language != 'en'
  181. ):
  182. infobox_id_lang = attribute.language
  183. infobox_id = url
  184. elif attribute_type == WDImageAttribute:
  185. # this attribute is an image.
  186. # replace the current image only the priority is lower
  187. # (the infobox contain only one image).
  188. if attribute.priority < img_src_priority:
  189. img_src = value
  190. img_src_priority = attribute.priority
  191. elif attribute_type == WDGeoAttribute:
  192. # geocoordinate link
  193. # use the area to get the OSM zoom
  194. # Note: ignre the unit (must be km² otherwise the calculation is wrong)
  195. # Should use normalized value p:P2046/psn:P2046/wikibase:quantityAmount
  196. area = attribute_result.get('P2046')
  197. osm_zoom = area_to_osm_zoom(area) if area else 19
  198. url = attribute.get_geo_url(attribute_result, osm_zoom=osm_zoom)
  199. if url:
  200. infobox_urls.append({'title': attribute.get_label(language), 'url': url, 'entity': attribute.name})
  201. else:
  202. infobox_attributes.append(
  203. {'label': attribute.get_label(language), 'value': value, 'entity': attribute.name}
  204. )
  205. if infobox_id:
  206. infobox_id = replace_http_by_https(infobox_id)
  207. # add the wikidata URL at the end
  208. infobox_urls.append({'title': 'Wikidata', 'url': attribute_result['item']})
  209. if img_src is None and len(infobox_attributes) == 0 and len(infobox_urls) == 1 and len(infobox_content) == 0:
  210. results.append({'url': infobox_urls[0]['url'], 'title': infobox_title, 'content': infobox_content})
  211. else:
  212. results.append(
  213. {
  214. 'infobox': infobox_title,
  215. 'id': infobox_id,
  216. 'content': infobox_content,
  217. 'img_src': img_src,
  218. 'urls': infobox_urls,
  219. 'attributes': infobox_attributes,
  220. }
  221. )
  222. return results
  223. def get_query(query, language):
  224. attributes = get_attributes(language)
  225. select = [a.get_select() for a in attributes]
  226. where = list(filter(lambda s: len(s) > 0, [a.get_where() for a in attributes]))
  227. wikibase_label = list(filter(lambda s: len(s) > 0, [a.get_wikibase_label() for a in attributes]))
  228. group_by = list(filter(lambda s: len(s) > 0, [a.get_group_by() for a in attributes]))
  229. query = (
  230. QUERY_TEMPLATE.replace('%QUERY%', sparql_string_escape(query))
  231. .replace('%SELECT%', ' '.join(select))
  232. .replace('%WHERE%', '\n '.join(where))
  233. .replace('%WIKIBASE_LABELS%', '\n '.join(wikibase_label))
  234. .replace('%GROUP_BY%', ' '.join(group_by))
  235. .replace('%LANGUAGE%', language)
  236. )
  237. return query, attributes
  238. def get_attributes(language):
  239. attributes = []
  240. def add_value(name):
  241. attributes.append(WDAttribute(name))
  242. def add_amount(name):
  243. attributes.append(WDAmountAttribute(name))
  244. def add_label(name):
  245. attributes.append(WDLabelAttribute(name))
  246. def add_url(name, url_id=None, **kwargs):
  247. attributes.append(WDURLAttribute(name, url_id, kwargs))
  248. def add_image(name, url_id=None, priority=1):
  249. attributes.append(WDImageAttribute(name, url_id, priority))
  250. def add_date(name):
  251. attributes.append(WDDateAttribute(name))
  252. # Dates
  253. for p in [
  254. 'P571', # inception date
  255. 'P576', # dissolution date
  256. 'P580', # start date
  257. 'P582', # end date
  258. 'P569', # date of birth
  259. 'P570', # date of death
  260. 'P619', # date of spacecraft launch
  261. 'P620',
  262. ]: # date of spacecraft landing
  263. add_date(p)
  264. for p in [
  265. 'P27', # country of citizenship
  266. 'P495', # country of origin
  267. 'P17', # country
  268. 'P159',
  269. ]: # headquarters location
  270. add_label(p)
  271. # Places
  272. for p in [
  273. 'P36', # capital
  274. 'P35', # head of state
  275. 'P6', # head of government
  276. 'P122', # basic form of government
  277. 'P37',
  278. ]: # official language
  279. add_label(p)
  280. add_value('P1082') # population
  281. add_amount('P2046') # area
  282. add_amount('P281') # postal code
  283. add_label('P38') # currency
  284. add_amount('P2048') # heigth (building)
  285. # Media
  286. for p in [
  287. 'P400', # platform (videogames, computing)
  288. 'P50', # author
  289. 'P170', # creator
  290. 'P57', # director
  291. 'P175', # performer
  292. 'P178', # developer
  293. 'P162', # producer
  294. 'P176', # manufacturer
  295. 'P58', # screenwriter
  296. 'P272', # production company
  297. 'P264', # record label
  298. 'P123', # publisher
  299. 'P449', # original network
  300. 'P750', # distributed by
  301. 'P86',
  302. ]: # composer
  303. add_label(p)
  304. add_date('P577') # publication date
  305. add_label('P136') # genre (music, film, artistic...)
  306. add_label('P364') # original language
  307. add_value('P212') # ISBN-13
  308. add_value('P957') # ISBN-10
  309. add_label('P275') # copyright license
  310. add_label('P277') # programming language
  311. add_value('P348') # version
  312. add_label('P840') # narrative location
  313. # Languages
  314. add_value('P1098') # number of speakers
  315. add_label('P282') # writing system
  316. add_label('P1018') # language regulatory body
  317. add_value('P218') # language code (ISO 639-1)
  318. # Other
  319. add_label('P169') # ceo
  320. add_label('P112') # founded by
  321. add_label('P1454') # legal form (company, organization)
  322. add_label('P137') # operator (service, facility, ...)
  323. add_label('P1029') # crew members (tripulation)
  324. add_label('P225') # taxon name
  325. add_value('P274') # chemical formula
  326. add_label('P1346') # winner (sports, contests, ...)
  327. add_value('P1120') # number of deaths
  328. add_value('P498') # currency code (ISO 4217)
  329. # URL
  330. add_url('P856', official=True) # official website
  331. attributes.append(WDArticle(language)) # wikipedia (user language)
  332. if not language.startswith('en'):
  333. attributes.append(WDArticle('en')) # wikipedia (english)
  334. add_url('P1324') # source code repository
  335. add_url('P1581') # blog
  336. add_url('P434', url_id='musicbrainz_artist')
  337. add_url('P435', url_id='musicbrainz_work')
  338. add_url('P436', url_id='musicbrainz_release_group')
  339. add_url('P966', url_id='musicbrainz_label')
  340. add_url('P345', url_id='imdb_id')
  341. add_url('P2397', url_id='youtube_channel')
  342. add_url('P1651', url_id='youtube_video')
  343. add_url('P2002', url_id='twitter_profile')
  344. add_url('P2013', url_id='facebook_profile')
  345. add_url('P2003', url_id='instagram_profile')
  346. # Map
  347. attributes.append(WDGeoAttribute('P625'))
  348. # Image
  349. add_image('P15', priority=1, url_id='wikimedia_image') # route map
  350. add_image('P242', priority=2, url_id='wikimedia_image') # locator map
  351. add_image('P154', priority=3, url_id='wikimedia_image') # logo
  352. add_image('P18', priority=4, url_id='wikimedia_image') # image
  353. add_image('P41', priority=5, url_id='wikimedia_image') # flag
  354. add_image('P2716', priority=6, url_id='wikimedia_image') # collage
  355. add_image('P2910', priority=7, url_id='wikimedia_image') # icon
  356. return attributes
  357. class WDAttribute:
  358. __slots__ = ('name',)
  359. def __init__(self, name):
  360. self.name = name
  361. def get_select(self):
  362. return '(group_concat(distinct ?{name};separator=", ") as ?{name}s)'.replace('{name}', self.name)
  363. def get_label(self, language):
  364. return get_label_for_entity(self.name, language)
  365. def get_where(self):
  366. return "OPTIONAL { ?item wdt:{name} ?{name} . }".replace('{name}', self.name)
  367. def get_wikibase_label(self):
  368. return ""
  369. def get_group_by(self):
  370. return ""
  371. def get_str(self, result, language):
  372. return result.get(self.name + 's')
  373. def __repr__(self):
  374. return '<' + str(type(self).__name__) + ':' + self.name + '>'
  375. class WDAmountAttribute(WDAttribute):
  376. def get_select(self):
  377. return '?{name} ?{name}Unit'.replace('{name}', self.name)
  378. def get_where(self):
  379. return """ OPTIONAL { ?item p:{name} ?{name}Node .
  380. ?{name}Node rdf:type wikibase:BestRank ; ps:{name} ?{name} .
  381. OPTIONAL { ?{name}Node psv:{name}/wikibase:quantityUnit ?{name}Unit. } }""".replace(
  382. '{name}', self.name
  383. )
  384. def get_group_by(self):
  385. return self.get_select()
  386. def get_str(self, result, language):
  387. value = result.get(self.name)
  388. unit = result.get(self.name + "Unit")
  389. if unit is not None:
  390. unit = unit.replace('http://www.wikidata.org/entity/', '')
  391. return value + " " + get_label_for_entity(unit, language)
  392. return value
  393. class WDArticle(WDAttribute):
  394. __slots__ = 'language', 'kwargs'
  395. def __init__(self, language, kwargs=None):
  396. super().__init__('wikipedia')
  397. self.language = language
  398. self.kwargs = kwargs or {}
  399. def get_label(self, language):
  400. # language parameter is ignored
  401. return "Wikipedia ({language})".replace('{language}', self.language)
  402. def get_select(self):
  403. return "?article{language} ?articleName{language}".replace('{language}', self.language)
  404. def get_where(self):
  405. return """OPTIONAL { ?article{language} schema:about ?item ;
  406. schema:inLanguage "{language}" ;
  407. schema:isPartOf <https://{language}.wikipedia.org/> ;
  408. schema:name ?articleName{language} . }""".replace(
  409. '{language}', self.language
  410. )
  411. def get_group_by(self):
  412. return self.get_select()
  413. def get_str(self, result, language):
  414. key = 'article{language}'.replace('{language}', self.language)
  415. return result.get(key)
  416. class WDLabelAttribute(WDAttribute):
  417. def get_select(self):
  418. return '(group_concat(distinct ?{name}Label;separator=", ") as ?{name}Labels)'.replace('{name}', self.name)
  419. def get_where(self):
  420. return "OPTIONAL { ?item wdt:{name} ?{name} . }".replace('{name}', self.name)
  421. def get_wikibase_label(self):
  422. return "?{name} rdfs:label ?{name}Label .".replace('{name}', self.name)
  423. def get_str(self, result, language):
  424. return result.get(self.name + 'Labels')
  425. class WDURLAttribute(WDAttribute):
  426. HTTP_WIKIMEDIA_IMAGE = 'http://commons.wikimedia.org/wiki/Special:FilePath/'
  427. __slots__ = 'url_id', 'kwargs'
  428. def __init__(self, name, url_id=None, kwargs=None):
  429. super().__init__(name)
  430. self.url_id = url_id
  431. self.kwargs = kwargs
  432. def get_str(self, result, language):
  433. value = result.get(self.name + 's')
  434. if self.url_id and value is not None and value != '':
  435. value = value.split(',')[0]
  436. url_id = self.url_id
  437. if value.startswith(WDURLAttribute.HTTP_WIKIMEDIA_IMAGE):
  438. value = value[len(WDURLAttribute.HTTP_WIKIMEDIA_IMAGE) :]
  439. url_id = 'wikimedia_image'
  440. return get_external_url(url_id, value)
  441. return value
  442. class WDGeoAttribute(WDAttribute):
  443. def get_label(self, language):
  444. return "OpenStreetMap"
  445. def get_select(self):
  446. return "?{name}Lat ?{name}Long".replace('{name}', self.name)
  447. def get_where(self):
  448. return """OPTIONAL { ?item p:{name}/psv:{name} [
  449. wikibase:geoLatitude ?{name}Lat ;
  450. wikibase:geoLongitude ?{name}Long ] }""".replace(
  451. '{name}', self.name
  452. )
  453. def get_group_by(self):
  454. return self.get_select()
  455. def get_str(self, result, language):
  456. latitude = result.get(self.name + 'Lat')
  457. longitude = result.get(self.name + 'Long')
  458. if latitude and longitude:
  459. return latitude + ' ' + longitude
  460. return None
  461. def get_geo_url(self, result, osm_zoom=19):
  462. latitude = result.get(self.name + 'Lat')
  463. longitude = result.get(self.name + 'Long')
  464. if latitude and longitude:
  465. return get_earth_coordinates_url(latitude, longitude, osm_zoom)
  466. return None
  467. class WDImageAttribute(WDURLAttribute):
  468. __slots__ = ('priority',)
  469. def __init__(self, name, url_id=None, priority=100):
  470. super().__init__(name, url_id)
  471. self.priority = priority
  472. class WDDateAttribute(WDAttribute):
  473. def get_select(self):
  474. return '?{name} ?{name}timePrecision ?{name}timeZone ?{name}timeCalendar'.replace('{name}', self.name)
  475. def get_where(self):
  476. # To remove duplicate, add
  477. # FILTER NOT EXISTS { ?item p:{name}/psv:{name}/wikibase:timeValue ?{name}bis FILTER (?{name}bis < ?{name}) }
  478. # this filter is too slow, so the response function ignore duplicate results
  479. # (see the seen_entities variable)
  480. return """OPTIONAL { ?item p:{name}/psv:{name} [
  481. wikibase:timeValue ?{name} ;
  482. wikibase:timePrecision ?{name}timePrecision ;
  483. wikibase:timeTimezone ?{name}timeZone ;
  484. wikibase:timeCalendarModel ?{name}timeCalendar ] . }
  485. hint:Prior hint:rangeSafe true;""".replace(
  486. '{name}', self.name
  487. )
  488. def get_group_by(self):
  489. return self.get_select()
  490. def format_8(self, value, locale):
  491. # precision: less than a year
  492. return value
  493. def format_9(self, value, locale):
  494. year = int(value)
  495. # precision: year
  496. if year < 1584:
  497. if year < 0:
  498. return str(year - 1)
  499. return str(year)
  500. timestamp = isoparse(value)
  501. return format_date(timestamp, format='yyyy', locale=locale)
  502. def format_10(self, value, locale):
  503. # precision: month
  504. timestamp = isoparse(value)
  505. return format_date(timestamp, format='MMMM y', locale=locale)
  506. def format_11(self, value, locale):
  507. # precision: day
  508. timestamp = isoparse(value)
  509. return format_date(timestamp, format='full', locale=locale)
  510. def format_13(self, value, locale):
  511. timestamp = isoparse(value)
  512. # precision: minute
  513. return (
  514. get_datetime_format(format, locale=locale)
  515. .replace("'", "")
  516. .replace('{0}', format_time(timestamp, 'full', tzinfo=None, locale=locale))
  517. .replace('{1}', format_date(timestamp, 'short', locale=locale))
  518. )
  519. def format_14(self, value, locale):
  520. # precision: second.
  521. return format_datetime(isoparse(value), format='full', locale=locale)
  522. DATE_FORMAT = {
  523. '0': ('format_8', 1000000000),
  524. '1': ('format_8', 100000000),
  525. '2': ('format_8', 10000000),
  526. '3': ('format_8', 1000000),
  527. '4': ('format_8', 100000),
  528. '5': ('format_8', 10000),
  529. '6': ('format_8', 1000),
  530. '7': ('format_8', 100),
  531. '8': ('format_8', 10),
  532. '9': ('format_9', 1), # year
  533. '10': ('format_10', 1), # month
  534. '11': ('format_11', 0), # day
  535. '12': ('format_13', 0), # hour (not supported by babel, display minute)
  536. '13': ('format_13', 0), # minute
  537. '14': ('format_14', 0), # second
  538. }
  539. def get_str(self, result, language):
  540. value = result.get(self.name)
  541. if value == '' or value is None:
  542. return None
  543. precision = result.get(self.name + 'timePrecision')
  544. date_format = WDDateAttribute.DATE_FORMAT.get(precision)
  545. if date_format is not None:
  546. format_method = getattr(self, date_format[0])
  547. precision = date_format[1]
  548. try:
  549. if precision >= 1:
  550. t = value.split('-')
  551. if value.startswith('-'):
  552. value = '-' + t[1]
  553. else:
  554. value = t[0]
  555. return format_method(value, language)
  556. except Exception:
  557. return value
  558. return value
  559. def debug_explain_wikidata_query(query, method='GET'):
  560. if method == 'GET':
  561. http_response = get(SPARQL_EXPLAIN_URL + '&' + urlencode({'query': query}), headers=get_headers())
  562. else:
  563. http_response = post(SPARQL_EXPLAIN_URL, data={'query': query}, headers=get_headers())
  564. http_response.raise_for_status()
  565. return http_response.content
  566. def init(engine_settings=None):
  567. # WIKIDATA_PROPERTIES : add unit symbols
  568. WIKIDATA_PROPERTIES.update(WIKIDATA_UNITS)
  569. # WIKIDATA_PROPERTIES : add property labels
  570. wikidata_property_names = []
  571. for attribute in get_attributes('en'):
  572. if type(attribute) in (WDAttribute, WDAmountAttribute, WDURLAttribute, WDDateAttribute, WDLabelAttribute):
  573. if attribute.name not in WIKIDATA_PROPERTIES:
  574. wikidata_property_names.append("wd:" + attribute.name)
  575. query = QUERY_PROPERTY_NAMES.replace('%ATTRIBUTES%', " ".join(wikidata_property_names))
  576. jsonresponse = send_wikidata_query(query)
  577. for result in jsonresponse.get('results', {}).get('bindings', {}):
  578. name = result['name']['value']
  579. lang = result['name']['xml:lang']
  580. entity_id = result['item']['value'].replace('http://www.wikidata.org/entity/', '')
  581. WIKIDATA_PROPERTIES[(entity_id, lang)] = name.capitalize()