Finna-JOKA-images / collect-joka.py
osma's picture
Upload folder using huggingface_hub
7497b1c verified
#!/usr/bin/env python
from finna_client import FinnaClient, IMAGE_BASE
import requests
import json
import os
import os.path
import logging
finna = FinnaClient()
logging.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO)
MAX_YEAR = 1940 # retrieve only images older than this (inclusive)
IMAGE_DIR = 'images'
# Facet filters that define the set of images we want to
FILTERS = [
'~format_ext_str_mv:"0/Image/"', # Images
'~building:"0/Museovirasto/"', # from Museovirasto (Finnish Heritage Agency)
'~hierarchy_parent_title:"JOKA Journalistinen kuva-arkisto"', # JOKA archive
'~usage_rights_ext_str_mv:"0/B BY/"', # CC By license
f'search_daterange_mv:"overlap|[* TO {MAX_YEAR}]"', # date up to MAX_YEAR
]
# Fields to include in the metadata records
FIELDS = [
'formats',
'id',
'imageRights',
'images',
'languages',
'nonPresenterAuthors',
'onlineUrls',
'presenters',
'rating',
'series',
'subjects',
'title',
'year',
'rawData',
]
def download_url_to_file(url, filename):
if os.path.exists(filename) and os.stat(filename).st_size > 0:
return # file already exists, no need to re-download
with requests.get(url, stream=True) as r:
r.raise_for_status()
with open(filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
with open('metadata.jsonl', 'w') as outfile:
page = 1
while True:
logging.info(f'Loading result page {page}')
result = finna.search(filters=FILTERS, fields=FIELDS, page=page)
if 'records' not in result:
logging.info('No more records, stopping.')
break
logging.debug(f'Got {len(result["records"])} records')
for record in result['records']:
image_url = IMAGE_BASE + record['images'][0]
image_file_out = os.path.join(IMAGE_DIR, record['id'] + '.jpg')
download_url_to_file(image_url, image_file_out)
record['file_name'] = image_file_out
json.dump(record, outfile)
print("", file=outfile)
page += 1