wikidata.py 24 KB

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