3 from django.db import models
4 from wikidata.client import Client
7 class Entity(models.Model):
8 WIKIDATA_PREFIX = 'https://www.wikidata.org/wiki/'
10 WIKIDATA_COORDINATE_LOCATION = 'P625'
12 WIKIDATA_IMAGE_QUERY = './w/api.php?action=query&titles={}&format=json&prop=imageinfo&iiprop=url&iiurlwidth=240&iiurlheight=200'
14 uri = models.CharField(max_length=255, unique=True, db_index=True)
15 label = models.CharField(max_length=1024, blank=True)
16 description = models.CharField(max_length=2048, blank=True)
17 wikipedia_link = models.CharField(max_length=1024, blank=True)
18 lat = models.FloatField(null=True, blank=True)
19 lon = models.FloatField(null=True, blank=True)
20 images = models.TextField(blank=True)
23 def is_interesting(self):
24 return self.wikipedia_link or (self.lat and self.lon) or len(self.images)>2
27 if self.uri.startswith(self.WIKIDATA_PREFIX):
28 self.populate_from_wikidata(
29 self.uri[len(self.WIKIDATA_PREFIX):]
32 def populate_from_wikidata(self, wikidata_id):
34 entity = client.get(wikidata_id)
36 self.label = entity.label.get('pl', entity.label) or ''
37 self.description = entity.description.get('pl', entity.description) or ''
38 sitelinks = entity.attributes.get('sitelinks', {})
39 self.wikipedia_link = sitelinks.get('plwiki', sitelinks.get('enwiki', {})).get('url') or ''
41 location_prop = client.get(self.WIKIDATA_COORDINATE_LOCATION)
42 location = entity.get(location_prop)
43 if location and location.globe.id == self.WIKIDATA_EARTH:
44 self.lat = location.latitude
45 self.lon = location.longitude
47 images = entity.getlist(client.get(self.WIKIDATA_IMAGE))
51 "url": image.image_url,
52 "page": image.page_url,
53 "resolution": image.image_resolution,
56 result = client.request(
57 self.WIKIDATA_IMAGE_QUERY.format(
58 urllib.parse.quote(image.title)
62 result_data = next(iter(result['query']['pages'].values()))['imageinfo'][0]
63 image_data['thumburl'] = result_data['thumburl']
64 image_data['thumbresolution'] = [
65 result_data['thumbwidth'],
66 result_data['thumbheight']
68 if 'responsiveUrls' in result_data:
69 image_data['responsiveUrls'] = result_data['responsiveUrls']
71 image_data_list.append(image_data)
73 self.images = json.dumps(image_data_list)
76 class Reference(models.Model):
77 book = models.ForeignKey('catalogue.Book', models.CASCADE)
78 entity = models.ForeignKey(Entity, models.CASCADE)
79 first_section = models.CharField(max_length=255)
82 unique_together = (('book', 'entity'),)