wikidata.py 25 KB

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