|
|
|
|
|
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 = 1917 |
|
IMAGE_DIR = 'images' |
|
|
|
|
|
FILTERS = [ |
|
'~format_ext_str_mv:"1/Image/Photo/"', |
|
'~building:"0/HKM/"', |
|
'~usage_rights_ext_str_mv:"0/B BY/"', |
|
f'search_daterange_mv:"overlap|[* TO {MAX_YEAR}]"', |
|
] |
|
|
|
|
|
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 |
|
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 |
|
|