wikidata.py 24 KB

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