wikidata.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. import json
  2. from requests import get
  3. from urllib import urlencode
  4. result_count = 1
  5. wikidata_host = 'https://www.wikidata.org'
  6. wikidata_api = wikidata_host + '/w/api.php'
  7. url_search = wikidata_api \
  8. + '?action=query&list=search&format=json'\
  9. + '&srnamespace=0&srprop=sectiontitle&{query}'
  10. url_detail = wikidata_api\
  11. + '?action=wbgetentities&format=json'\
  12. + '&props=labels%7Cinfo%7Csitelinks'\
  13. + '%7Csitelinks%2Furls%7Cdescriptions%7Cclaims'\
  14. + '&{query}'
  15. url_map = 'https://www.openstreetmap.org/'\
  16. + '?lat={latitude}&lon={longitude}&zoom={zoom}&layers=M'
  17. def request(query, params):
  18. params['url'] = url_search.format(
  19. query=urlencode({'srsearch': query,
  20. 'srlimit': result_count}))
  21. return params
  22. def response(resp):
  23. results = []
  24. search_res = json.loads(resp.text)
  25. wikidata_ids = set()
  26. for r in search_res.get('query', {}).get('search', {}):
  27. wikidata_ids.add(r.get('title', ''))
  28. language = resp.search_params['language'].split('_')[0]
  29. if language == 'all':
  30. language = 'en'
  31. url = url_detail.format(query=urlencode({'ids': '|'.join(wikidata_ids),
  32. 'languages': language + '|en'}))
  33. htmlresponse = get(url)
  34. jsonresponse = json.loads(htmlresponse.content)
  35. for wikidata_id in wikidata_ids:
  36. results = results + getDetail(jsonresponse, wikidata_id, language)
  37. return results
  38. def getDetail(jsonresponse, wikidata_id, language):
  39. results = []
  40. urls = []
  41. attributes = []
  42. result = jsonresponse.get('entities', {}).get(wikidata_id, {})
  43. title = result.get('labels', {}).get(language, {}).get('value', None)
  44. if title is None:
  45. title = result.get('labels', {}).get('en', {}).get('value', None)
  46. if title is None:
  47. return results
  48. description = result\
  49. .get('descriptions', {})\
  50. .get(language, {})\
  51. .get('value', None)
  52. if description is None:
  53. description = result\
  54. .get('descriptions', {})\
  55. .get('en', {})\
  56. .get('value', '')
  57. claims = result.get('claims', {})
  58. official_website = get_string(claims, 'P856', None)
  59. if official_website is not None:
  60. urls.append({'title': 'Official site', 'url': official_website})
  61. results.append({'title': title, 'url': official_website})
  62. wikipedia_link_count = 0
  63. if language != 'en':
  64. wikipedia_link_count += add_url(urls,
  65. 'Wikipedia (' + language + ')',
  66. get_wikilink(result, language +
  67. 'wiki'))
  68. wikipedia_en_link = get_wikilink(result, 'enwiki')
  69. wikipedia_link_count += add_url(urls,
  70. 'Wikipedia (en)',
  71. wikipedia_en_link)
  72. if wikipedia_link_count == 0:
  73. misc_language = get_wiki_firstlanguage(result, 'wiki')
  74. if misc_language is not None:
  75. add_url(urls,
  76. 'Wikipedia (' + misc_language + ')',
  77. get_wikilink(result, misc_language + 'wiki'))
  78. if language != 'en':
  79. add_url(urls,
  80. 'Wiki voyage (' + language + ')',
  81. get_wikilink(result, language + 'wikivoyage'))
  82. add_url(urls,
  83. 'Wiki voyage (en)',
  84. get_wikilink(result, 'enwikivoyage'))
  85. if language != 'en':
  86. add_url(urls,
  87. 'Wikiquote (' + language + ')',
  88. get_wikilink(result, language + 'wikiquote'))
  89. add_url(urls,
  90. 'Wikiquote (en)',
  91. get_wikilink(result, 'enwikiquote'))
  92. add_url(urls,
  93. 'Commons wiki',
  94. get_wikilink(result, 'commonswiki'))
  95. add_url(urls,
  96. 'Location',
  97. get_geolink(claims, 'P625', None))
  98. add_url(urls,
  99. 'Wikidata',
  100. 'https://www.wikidata.org/wiki/'
  101. + wikidata_id + '?uselang=' + language)
  102. musicbrainz_work_id = get_string(claims, 'P435')
  103. if musicbrainz_work_id is not None:
  104. add_url(urls,
  105. 'MusicBrainz',
  106. 'http://musicbrainz.org/work/'
  107. + musicbrainz_work_id)
  108. musicbrainz_artist_id = get_string(claims, 'P434')
  109. if musicbrainz_artist_id is not None:
  110. add_url(urls,
  111. 'MusicBrainz',
  112. 'http://musicbrainz.org/artist/'
  113. + musicbrainz_artist_id)
  114. musicbrainz_release_group_id = get_string(claims, 'P436')
  115. if musicbrainz_release_group_id is not None:
  116. add_url(urls,
  117. 'MusicBrainz',
  118. 'http://musicbrainz.org/release-group/'
  119. + musicbrainz_release_group_id)
  120. musicbrainz_label_id = get_string(claims, 'P966')
  121. if musicbrainz_label_id is not None:
  122. add_url(urls,
  123. 'MusicBrainz',
  124. 'http://musicbrainz.org/label/'
  125. + musicbrainz_label_id)
  126. # musicbrainz_area_id = get_string(claims, 'P982')
  127. # P1407 MusicBrainz series ID
  128. # P1004 MusicBrainz place ID
  129. # P1330 MusicBrainz instrument ID
  130. # P1407 MusicBrainz series ID
  131. postal_code = get_string(claims, 'P281', None)
  132. if postal_code is not None:
  133. attributes.append({'label': 'Postal code(s)', 'value': postal_code})
  134. date_of_birth = get_time(claims, 'P569', None)
  135. if date_of_birth is not None:
  136. attributes.append({'label': 'Date of birth', 'value': date_of_birth})
  137. date_of_death = get_time(claims, 'P570', None)
  138. if date_of_death is not None:
  139. attributes.append({'label': 'Date of death', 'value': date_of_death})
  140. if len(attributes) == 0 and len(urls) == 2 and len(description) == 0:
  141. results.append({
  142. 'url': urls[0]['url'],
  143. 'title': title,
  144. 'content': description
  145. })
  146. else:
  147. results.append({
  148. 'infobox': title,
  149. 'id': wikipedia_en_link,
  150. 'content': description,
  151. 'attributes': attributes,
  152. 'urls': urls
  153. })
  154. return results
  155. def add_url(urls, title, url):
  156. if url is not None:
  157. urls.append({'title': title, 'url': url})
  158. return 1
  159. else:
  160. return 0
  161. def get_mainsnak(claims, propertyName):
  162. propValue = claims.get(propertyName, {})
  163. if len(propValue) == 0:
  164. return None
  165. propValue = propValue[0].get('mainsnak', None)
  166. return propValue
  167. def get_string(claims, propertyName, defaultValue=None):
  168. propValue = claims.get(propertyName, {})
  169. if len(propValue) == 0:
  170. return defaultValue
  171. result = []
  172. for e in propValue:
  173. mainsnak = e.get('mainsnak', {})
  174. datavalue = mainsnak.get('datavalue', {})
  175. if datavalue is not None:
  176. result.append(datavalue.get('value', ''))
  177. if len(result) == 0:
  178. return defaultValue
  179. else:
  180. #TODO handle multiple urls
  181. return result[0]
  182. def get_time(claims, propertyName, defaultValue=None):
  183. propValue = claims.get(propertyName, {})
  184. if len(propValue) == 0:
  185. return defaultValue
  186. result = []
  187. for e in propValue:
  188. mainsnak = e.get('mainsnak', {})
  189. datavalue = mainsnak.get('datavalue', {})
  190. if datavalue is not None:
  191. value = datavalue.get('value', '')
  192. result.append(value.get('time', ''))
  193. if len(result) == 0:
  194. return defaultValue
  195. else:
  196. return ', '.join(result)
  197. def get_geolink(claims, propertyName, defaultValue=''):
  198. mainsnak = get_mainsnak(claims, propertyName)
  199. if mainsnak is None:
  200. return defaultValue
  201. datatype = mainsnak.get('datatype', '')
  202. datavalue = mainsnak.get('datavalue', {})
  203. if datatype != 'globe-coordinate':
  204. return defaultValue
  205. value = datavalue.get('value', {})
  206. precision = value.get('precision', 0.0002)
  207. # there is no zoom information, deduce from precision (error prone)
  208. # samples :
  209. # 13 --> 5
  210. # 1 --> 6
  211. # 0.016666666666667 --> 9
  212. # 0.00027777777777778 --> 19
  213. # wolframalpha :
  214. # quadratic fit { {13, 5}, {1, 6}, {0.0166666, 9}, {0.0002777777,19}}
  215. # 14.1186-8.8322 x+0.625447 x^2
  216. if precision < 0.0003:
  217. zoom = 19
  218. else:
  219. zoom = int(15 - precision*8.8322 + precision*precision*0.625447)
  220. url = url_map\
  221. .replace('{latitude}', str(value.get('latitude', 0)))\
  222. .replace('{longitude}', str(value.get('longitude', 0)))\
  223. .replace('{zoom}', str(zoom))
  224. return url
  225. def get_wikilink(result, wikiid):
  226. url = result.get('sitelinks', {}).get(wikiid, {}).get('url', None)
  227. if url is None:
  228. return url
  229. elif url.startswith('http://'):
  230. url = url.replace('http://', 'https://')
  231. elif url.startswith('//'):
  232. url = 'https:' + url
  233. return url
  234. def get_wiki_firstlanguage(result, wikipatternid):
  235. for k in result.get('sitelinks', {}).keys():
  236. if k.endswith(wikipatternid) and len(k) == (2+len(wikipatternid)):
  237. return k[0:2]
  238. return None