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.
5 from io import StringIO
8 from urllib.request import FancyURLopener
9 from wikidata.client import Client
10 from catalogue.constants import WIKIDATA
13 class URLOpener(FancyURLopener):
19 class FlickrError(Exception):
23 def get_flickr_data(url):
24 m = re.match(r'(https?://)?(www\.|secure\.)?flickr\.com/photos/(?P<author>[^/]+)/(?P<img>\d+)/?', url)
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)
30 html = URLOpener().open(url).read().decode('utf-8')
32 raise FlickrError('Error reading page')
33 match = re.search(r'<a href="([^"]*)"[^>]* rel="license ', html)
35 raise FlickrError('License not found.')
37 license_url = match.group(1)
38 re_license = re.compile(r'https?://creativecommons.org/licenses/([^/]*)/([^/]*)/.*')
39 m = re_license.match(license_url)
41 re_pd = re.compile(r'https?://creativecommons.org/publicdomain/([^/]*)/([^/]*)/.*')
42 m = re_pd.match(license_url)
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)
48 license_name = 'Public domain'
50 license_name = 'CC %s %s' % (m.group(1).upper(), m.group(2))
51 m = re.search(r'<a[^>]* class="owner-name [^>]*>([^<]*)<', html)
53 author = "%s@Flickr" % m.group(1)
55 raise FlickrError('Error reading author name.')
56 m = re.search(r'<h1[^>]*>(.*?)</h1>', html, re.S)
58 raise FlickrError('Error reading image title.')
59 title = m.group(1).strip()
60 m = re.search(r'modelExport: (\{.*\})', html)
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.')
67 'source_url': base_url,
68 'license_url': license_url,
69 'license_name': license_name,
72 'download_url': download_url,
76 def get_wikimedia_data(url):
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'}
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'}
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'))
88 d = list(d['query']['pages'].values())[0]['imageinfo'][0]
89 ext = d['extmetadata']
92 'title': ext['ObjectName']['value'],
94 'source_url': d['descriptionurl'],
95 'download_url': d['url'],
96 'license_url': ext.get('LicenseUrl', {}).get('value', ''),
97 'license_name': ext['LicenseShortName']['value'],
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)
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))
110 if meta['license_name'] == 'Public domain':
111 meta['license_name'] = 'domena publiczna'
112 meta['license_url'] = 'https://pl.wikipedia.org/wiki/Domena_publiczna'
118 def get_mnw_data(url):
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'}
123 nr = url.rsplit('/', 1)[-1]
128 'https://cyfrowe-api.mnw.art.pl/api/object/{}/csv'.format(nr)
129 ).read().decode('utf-8')
136 while f'authors.{i}.name' in d:
137 authors.append(d[f'authors.{i}.name'])
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'
148 'author': ', '.join(authors),
150 'download_url': 'https://cyfrowe-cdn.mnw.art.pl/upload/multimedia/{}.{}'.format(
152 d['image.extension'],
154 'license_url': license_url,
155 'license_name': license_name,
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)