Use Wikidata for cover imports from Commons.
[redakcja.git] / src / cover / utils.py
1 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
3 #
4 import csv
5 from io import StringIO
6 import json
7 import re
8 from urllib.request import FancyURLopener
9 from wikidata.client import Client
10 from catalogue.constants import WIKIDATA
11
12
13 class URLOpener(FancyURLopener):
14     @property
15     def version(self):
16         return 'FNP Redakcja'
17
18
19 class FlickrError(Exception):
20     pass
21
22
23 def get_flickr_data(url):
24     m = re.match(r'(https?://)?(www\.|secure\.)?flickr\.com/photos/(?P<author>[^/]+)/(?P<img>\d+)/?', url)
25     if not m:
26         raise FlickrError("It doesn't look like Flickr URL.")
27     author_slug, img_id = m.group('author'), m.group('img')
28     base_url = "https://www.flickr.com/photos/%s/%s/" % (author_slug, img_id)
29     try:
30         html = URLOpener().open(url).read().decode('utf-8')
31     except IOError:
32         raise FlickrError('Error reading page')
33     match = re.search(r'<a href="([^"]*)"[^>]* rel="license ', html)
34     if not match:
35         raise FlickrError('License not found.')
36     else:
37         license_url = match.group(1)
38         re_license = re.compile(r'https?://creativecommons.org/licenses/([^/]*)/([^/]*)/.*')
39         m = re_license.match(license_url)
40         if not m:
41             re_pd = re.compile(r'https?://creativecommons.org/publicdomain/([^/]*)/([^/]*)/.*')
42             m = re_pd.match(license_url)
43             if not m:
44                 raise FlickrError('License does not look like CC: %s' % license_url)
45             if m.group(1).lower() == 'zero':
46                 license_name = 'Public domain (CC0 %s)' % m.group(2)
47             else:
48                 license_name = 'Public domain'
49         else:
50             license_name = 'CC %s %s' % (m.group(1).upper(), m.group(2))
51     m = re.search(r'<a[^>]* class="owner-name [^>]*>([^<]*)<', html)
52     if m:
53         author = "%s@Flickr" % m.group(1)
54     else:
55         raise FlickrError('Error reading author name.')
56     m = re.search(r'<h1[^>]*>(.*?)</h1>', html, re.S)
57     if not m:
58         raise FlickrError('Error reading image title.')
59     title = m.group(1).strip()
60     m = re.search(r'modelExport: (\{.*\})', html)
61     try:
62         assert m
63         download_url = 'https:' + json.loads(m.group(1))['main']['photo-models'][0]['sizes']['o']['url']
64     except (AssertionError, ValueError, IndexError, KeyError):
65         raise FlickrError('Error reading image URL.')
66     return {
67         'source_url': base_url,
68         'license_url': license_url,
69         'license_name': license_name,
70         'author': author,
71         'title': title,
72         'download_url': download_url,
73     }
74
75
76 def get_wikimedia_data(url):
77     """
78     >>> get_wikimedia_data('https://commons.wikimedia.org/wiki/File:Valdai_IverskyMon_asv2018_img47.jpg')
79     {'title': 'Valdai IverskyMon asv2018 img47', 'author': 'A.Savin', 'source_url': 'https://commons.wikimedia.org/wiki/File:Valdai_IverskyMon_asv2018_img47.jpg', 'download_url': 'https://upload.wikimedia.org/wikipedia/commons/4/43/Valdai_IverskyMon_asv2018_img47.jpg', 'license_url': 'http://artlibre.org/licence/lal/en', 'license_name': 'FAL'}
80
81     >>> get_wikimedia_data('https://commons.wikimedia.org/wiki/File:Pymonenko_A_boy_in_a_straw_hat.jpg')
82     {'title': 'Chłopiec w słomkowym kapeluszu', 'author': 'Mykola Pymonenko', 'source_url': 'https://commons.wikimedia.org/wiki/File:Pymonenko_A_boy_in_a_straw_hat.jpg', 'download_url': 'https://upload.wikimedia.org/wikipedia/commons/9/9b/Pymonenko_A_boy_in_a_straw_hat.jpg', 'license_url': 'https://pl.wikipedia.org/wiki/Domena_publiczna', 'license_name': 'domena publiczna'}
83
84     """
85     file_name = url.rsplit('/', 1)[-1].rsplit(':', 1)[-1]
86     d = json.loads(URLOpener().open('https://commons.wikimedia.org/w/api.php?action=query&titles=File:{}&prop=imageinfo&iiprop=url|user|extmetadata&iimetadataversion=latest&format=json'.format(file_name)).read().decode('utf-8'))
87
88     d = list(d['query']['pages'].values())[0]['imageinfo'][0]
89     ext = d['extmetadata']
90
91     meta = {
92         'title': ext['ObjectName']['value'],
93         'author': d['user'],
94         'source_url': d['descriptionurl'],
95         'download_url': d['url'],
96         'license_url': ext.get('LicenseUrl', {}).get('value', ''),
97         'license_name': ext['LicenseShortName']['value'],
98     }
99
100     # There are Wikidata links in ObjectName sametimes. Let's use it.
101     wikidata_match = re.search(r'wikidata\.org/wiki/(Q\d+)', meta['title'])
102     if wikidata_match is not None:
103         qitem = wikidata_match.group(1)
104         client = Client()
105         entity = client.get(qitem)
106         meta['title'] = entity.label.get('pl', str(entity.label))
107         author = entity.get(client.get(WIKIDATA.CREATOR))
108         meta['author'] = author.label.get('pl', str(author.label))
109
110     if meta['license_name'] == 'Public domain':
111         meta['license_name'] = 'domena publiczna'
112         meta['license_url'] = 'https://pl.wikipedia.org/wiki/Domena_publiczna'
113
114
115     return meta
116
117
118 def get_mnw_data(url):
119     """
120     >>> get_mnw_data('https://cyfrowe.mnw.art.pl/pl/katalog/511078')
121     {'title': 'Chłopka (Baba ukraińska)', 'author': 'Krzyżanowski, Konrad (1872-1922)', 'source_url': 'https://cyfrowe.mnw.art.pl/pl/katalog/511078', 'download_url': 'https://cyfrowe-cdn.mnw.art.pl/upload/multimedia/32/60/3260ae1704cc530cc62befa9b7d58cbd.jpg', 'license_url': 'https://pl.wikipedia.org/wiki/Domena_publiczna', 'license_name': 'domena publiczna'}
122     """
123     nr = url.rsplit('/', 1)[-1]
124     d = list(
125         csv.DictReader(
126             StringIO(
127                 URLOpener().open(
128                     'https://cyfrowe-api.mnw.art.pl/api/object/{}/csv'.format(nr)
129                 ).read().decode('utf-8')
130             )
131         )
132     )[0]
133
134     authors = []
135     i = 0
136     while f'authors.{i}.name' in d:
137         authors.append(d[f'authors.{i}.name'])
138         i += 1
139
140     license_url = d['copyrights.0.link']
141     license_name = d['copyrights.0.name']
142     if license_name == 'DOMENA PUBLICZNA':
143         license_name = 'domena publiczna'
144         license_url = 'https://pl.wikipedia.org/wiki/Domena_publiczna'
145         
146     return {
147         'title': d['title'],
148         'author': ', '.join(authors),
149         'source_url': url,
150         'download_url': 'https://cyfrowe-cdn.mnw.art.pl/upload/multimedia/{}.{}'.format(
151             d['image.filePath'],
152             d['image.extension'],
153         ),
154         'license_url': license_url,
155         'license_name': license_name,
156     }
157
158
159 def get_import_data(url):
160     if re.match(r'(https?://)?(www\.|secure\.)?flickr\.com/', url):
161         return get_flickr_data(url)
162     if re.match(r'(https?://)?(commons|upload)\.wikimedia\.org/', url):
163         return get_wikimedia_data(url)
164     if re.match(r'(https?://)?cyfrowe\.mnw\.art\.pl/', url):
165         return get_mnw_data(url)