wikidata.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. import json
  2. from requests import get
  3. from urllib import urlencode
  4. resultCount=1
  5. urlSearch = 'https://www.wikidata.org/w/api.php?action=query&list=search&format=json&srnamespace=0&srprop=sectiontitle&{query}'
  6. urlDetail = 'https://www.wikidata.org/w/api.php?action=wbgetentities&format=json&props=labels%7Cinfo%7Csitelinks%7Csitelinks%2Furls%7Cdescriptions%7Cclaims&{query}'
  7. urlMap = 'https://www.openstreetmap.org/?lat={latitude}&lon={longitude}&zoom={zoom}&layers=M'
  8. def request(query, params):
  9. params['url'] = urlSearch.format(query=urlencode({'srsearch': query, 'srlimit': resultCount}))
  10. return params
  11. def response(resp):
  12. results = []
  13. search_res = json.loads(resp.text)
  14. wikidata_ids = set()
  15. for r in search_res.get('query', {}).get('search', {}):
  16. wikidata_ids.add(r.get('title', ''))
  17. language = resp.search_params['language'].split('_')[0]
  18. if language == 'all':
  19. language = 'en'
  20. url = urlDetail.format(query=urlencode({'ids': '|'.join(wikidata_ids), 'languages': language + '|en'}))
  21. htmlresponse = get(url)
  22. jsonresponse = json.loads(htmlresponse.content)
  23. for wikidata_id in wikidata_ids:
  24. results = results + getDetail(jsonresponse, wikidata_id, language)
  25. return results
  26. def getDetail(jsonresponse, wikidata_id, language):
  27. result = jsonresponse.get('entities', {}).get(wikidata_id, {})
  28. title = result.get('labels', {}).get(language, {}).get('value', None)
  29. if title == None:
  30. title = result.get('labels', {}).get('en', {}).get('value', wikidata_id)
  31. results = []
  32. urls = []
  33. attributes = []
  34. description = result.get('descriptions', {}).get(language, {}).get('value', '')
  35. if description == '':
  36. description = result.get('descriptions', {}).get('en', {}).get('value', '')
  37. claims = result.get('claims', {})
  38. official_website = get_string(claims, 'P856', None)
  39. if official_website != None:
  40. urls.append({ 'title' : 'Official site', 'url': official_website })
  41. results.append({ 'title': title, 'url' : official_website })
  42. if language != 'en':
  43. add_url(urls, 'Wikipedia (' + language + ')', get_wikilink(result, language + 'wiki'))
  44. wikipedia_en_link = get_wikilink(result, 'enwiki')
  45. add_url(urls, 'Wikipedia (en)', wikipedia_en_link)
  46. if language != 'en':
  47. add_url(urls, 'Wiki voyage (' + language + ')', get_wikilink(result, language + 'wikivoyage'))
  48. add_url(urls, 'Wiki voyage (en)', get_wikilink(result, 'enwikivoyage'))
  49. if language != 'en':
  50. add_url(urls, 'Wikiquote (' + language + ')', get_wikilink(result, language + 'wikiquote'))
  51. add_url(urls, 'Wikiquote (en)', get_wikilink(result, 'enwikiquote'))
  52. add_url(urls, 'Commons wiki', get_wikilink(result, 'commonswiki'))
  53. add_url(urls, 'Location', get_geolink(claims, 'P625', None))
  54. add_url(urls, 'Wikidata', 'https://www.wikidata.org/wiki/' + wikidata_id + '?uselang='+ language)
  55. musicbrainz_work_id = get_string(claims, 'P435')
  56. if musicbrainz_work_id != None:
  57. add_url(urls, 'MusicBrainz', 'http://musicbrainz.org/work/' + musicbrainz_work_id)
  58. musicbrainz_artist_id = get_string(claims, 'P434')
  59. if musicbrainz_artist_id != None:
  60. add_url(urls, 'MusicBrainz', 'http://musicbrainz.org/artist/' + musicbrainz_artist_id)
  61. musicbrainz_release_group_id = get_string(claims, 'P436')
  62. if musicbrainz_release_group_id != None:
  63. add_url(urls, 'MusicBrainz', 'http://musicbrainz.org/release-group/' + musicbrainz_release_group_id)
  64. musicbrainz_label_id = get_string(claims, 'P966')
  65. if musicbrainz_label_id != None:
  66. add_url(urls, 'MusicBrainz', 'http://musicbrainz.org/label/' + musicbrainz_label_id)
  67. # musicbrainz_area_id = get_string(claims, 'P982')
  68. # P1407 MusicBrainz series ID
  69. # P1004 MusicBrainz place ID
  70. # P1330 MusicBrainz instrument ID
  71. # P1407 MusicBrainz series ID
  72. postal_code = get_string(claims, 'P281', None)
  73. if postal_code != None:
  74. attributes.append({'label' : 'Postal code(s)', 'value' : postal_code})
  75. date_of_birth = get_time(claims, 'P569', None)
  76. if date_of_birth != None:
  77. attributes.append({'label' : 'Date of birth', 'value' : date_of_birth})
  78. date_of_death = get_time(claims, 'P570', None)
  79. if date_of_death != None:
  80. attributes.append({'label' : 'Date of death', 'value' : date_of_death})
  81. results.append({
  82. 'infobox' : title,
  83. 'id' : wikipedia_en_link,
  84. 'content' : description,
  85. 'attributes' : attributes,
  86. 'urls' : urls
  87. })
  88. return results
  89. def add_url(urls, title, url):
  90. if url != None:
  91. urls.append({'title' : title, 'url' : url})
  92. def get_mainsnak(claims, propertyName):
  93. propValue = claims.get(propertyName, {})
  94. if len(propValue) == 0:
  95. return None
  96. propValue = propValue[0].get('mainsnak', None)
  97. return propValue
  98. def get_string(claims, propertyName, defaultValue=None):
  99. propValue = claims.get(propertyName, {})
  100. if len(propValue) == 0:
  101. return defaultValue
  102. result = []
  103. for e in propValue:
  104. mainsnak = e.get('mainsnak', {})
  105. datavalue = mainsnak.get('datavalue', {})
  106. if datavalue != None:
  107. result.append(datavalue.get('value', ''))
  108. if len(result) == 0:
  109. return defaultValue
  110. else:
  111. return ', '.join(result)
  112. def get_time(claims, propertyName, defaultValue=None):
  113. propValue = claims.get(propertyName, {})
  114. if len(propValue) == 0:
  115. return defaultValue
  116. result = []
  117. for e in propValue:
  118. mainsnak = e.get('mainsnak', {})
  119. datavalue = mainsnak.get('datavalue', {})
  120. if datavalue != None:
  121. value = datavalue.get('value', '')
  122. result.append(value.get('time', ''))
  123. if len(result) == 0:
  124. return defaultValue
  125. else:
  126. return ', '.join(result)
  127. def get_geolink(claims, propertyName, defaultValue=''):
  128. mainsnak = get_mainsnak(claims, propertyName)
  129. if mainsnak == None:
  130. return defaultValue
  131. datatype = mainsnak.get('datatype', '')
  132. datavalue = mainsnak.get('datavalue', {})
  133. if datatype != 'globe-coordinate':
  134. return defaultValue
  135. value = datavalue.get('value', {})
  136. precision = value.get('precision', 0.0002)
  137. # there is no zoom information, deduce from precision (error prone)
  138. # samples :
  139. # 13 --> 5
  140. # 1 --> 6
  141. # 0.016666666666667 --> 9
  142. # 0.00027777777777778 --> 19
  143. # wolframalpha : quadratic fit { {13, 5}, {1, 6}, {0.0166666, 9}, {0.0002777777,19}}
  144. # 14.1186-8.8322 x+0.625447 x^2
  145. if precision < 0.0003:
  146. zoom = 19
  147. else:
  148. zoom = int(15 - precision*8.8322 + precision*precision*0.625447)
  149. url = urlMap.replace('{latitude}', str(value.get('latitude',0))).replace('{longitude}', str(value.get('longitude',0))).replace('{zoom}', str(zoom))
  150. return url
  151. def get_wikilink(result, wikiid):
  152. url = result.get('sitelinks', {}).get(wikiid, {}).get('url', None)
  153. if url == None:
  154. return url
  155. elif url.startswith('http://'):
  156. url = url.replace('http://', 'https://')
  157. elif url.startswith('//'):
  158. url = 'https:' + url
  159. return url