from __future__ import annotations import hashlib import json import re import unicodedata from pathlib import Path from typing import Any from urllib.parse import urlparse from xml.etree import ElementTree as ET from datasets import Features, Image, Sequence, Value NS = { "md": "http://www.loc.gov/mods/v3", "h": "http://www.w3.org/1999/xhtml", "mix": "http://www.loc.gov/mix/v10", "os": "http://a9.com/-/spec/opensearch/1.1/", } XML_LANG = "{http://www.w3.org/XML/1998/namespace}lang" SELECTED_EDITIONS: dict[str, dict[str, str]] = { "billeder": { "title": "Billeder", "identifier": "/images/billed/2010/okt/billeder/da/", "source_kind": "photographs_prints_drawings", "decision": "included", "reason": "Primary visual image collection: photographs, drawings, engravings and postcards.", }, "maps": { "title": "Kort og Atlas", "identifier": "/maps/kortsa/2012/jul/kortatlas/da/", "source_kind": "maps_atlases", "decision": "included_separate_subset", "reason": "Cartographic visual material. Kept separable with source_subset=maps because it can contain labels.", }, } EXCLUDED_EDITION_REASONS: dict[str, str] = { "/images/luftfo/2011/maj/luftfoto": "excluded: aerial photographs requested out of scope", "/pamphlets/": "excluded: pamphlets/printed matter are text-heavy", "/letters/": "excluded: letters are text-heavy", "/books/": "excluded: books are text-heavy", "/manus/": "excluded: manuscripts are text-heavy", "Danske aviser 1666-1883": "excluded: newspapers requested out of scope", } LICENSE_QUERIES = [ "Fri af ophavsret", "Materialet er fri af ophavsret", "Public Domain", "Public Domain Mark", "public domain mark", "No known rights", "No known copyright", "Ingen kendte rettigheder", "Creative Commons", "creativecommons", "creativecommons.org/licenses/by", "creativecommons.org/licenses/by-sa", "CC-BY", "CC BY", "CC-BY-SA", "CC BY-SA", "Navngivelse", "Del på samme vilkår", ] def local_name(tag: str) -> str: return tag.rsplit("}", 1)[-1] if "}" in tag else tag def text_content(element: ET.Element | None) -> str | None: if element is None: return None text = " ".join(part.strip() for part in element.itertext() if part and part.strip()) return re.sub(r"\s+", " ", text).strip() or None def direct_child_texts(parent: ET.Element, child_name: str, lang: str | None = None) -> list[str]: out: list[str] = [] for child in list(parent): if local_name(child.tag) != child_name: continue if lang is not None and child.get(XML_LANG) != lang: continue value = text_content(child) if value: out.append(value) return dedupe_preserve(out) def find_texts(root: ET.Element, path: str) -> list[str]: return dedupe_preserve([value for value in (text_content(e) for e in root.findall(path, NS)) if value]) def dedupe_preserve(values: list[str]) -> list[str]: seen: set[str] = set() out: list[str] = [] for value in values: if value not in seen: seen.add(value) out.append(value) return out def slugify(value: str, max_len: int = 96) -> str: normalized = unicodedata.normalize("NFKD", value).encode("ascii", "ignore").decode("ascii") slug = re.sub(r"[^A-Za-z0-9._-]+", "-", normalized).strip("-._").lower() return (slug or hashlib.sha1(value.encode("utf-8")).hexdigest()[:16])[:max_len] def object_id_from_record_id(record_id: str) -> str: match = re.search(r"object\d+", record_id) return match.group(0) if match else slugify(record_id) def kbl_page_url(record_id: str) -> str: if record_id.startswith("http"): parsed = urlparse(record_id) path = parsed.path if path.startswith("/cop/"): path = path[4:] else: path = record_id path = path.strip() if path.startswith("/"): return f"https://digitalesamlinger.kb.dk{path}/da/" return path def normalize_iiif_image_url(image_url: str, max_size: int = 1600) -> str: # KBL IIIF URLs generally end in /full/full/0/native.jpg. Keep the original # in metadata and use a bounded training URL for download. image_url = image_url.replace("http://", "https://", 1) replacements = [ ("/full/full/0/native.jpg", f"/full/!{max_size},/0/native.jpg"), ("/full/full/0/default.jpg", f"/full/!{max_size},/0/default.jpg"), ] for old, new in replacements: if old in image_url: return image_url.replace(old, new) return image_url def classify_license(access_conditions: list[str], raw_xml: str) -> tuple[bool, str | None, str | None, str | None]: rights_text = " | ".join(access_conditions) haystack = f"{rights_text}\n{raw_xml}".lower() if "by-nc" in haystack or "noncommercial" in haystack or "non-commercial" in haystack: return False, None, None, None if "by-nd" in haystack or "noderivs" in haystack or "no derivatives" in haystack: return False, None, None, None contradictory_rights = any( phrase in rights_text.lower() for phrase in [ "materialet er beskyttet af ophavsret", "materialet er muligvis beskyttet af ophavsret", "protected by copyright", "may not be reproduced", ] ) if "creativecommons.org/licenses/by-sa" in haystack or "cc-by-sa" in haystack or "cc by-sa" in haystack: return True, "CC BY-SA", "cc-by-sa", rights_text or "CC BY-SA" if "creativecommons.org/licenses/by/" in haystack or "cc-by" in haystack or "cc by" in haystack: return True, "CC BY", "cc-by", rights_text or "CC BY" if contradictory_rights: return False, None, None, rights_text or None if ( "fri af ophavsret" in haystack or "public domain" in haystack or "publicdomain/mark" in haystack or "public domain mark" in haystack ): return True, "Public Domain", "public-domain", rights_text or "Public Domain" if "no known rights" in haystack or "no known copyright" in haystack or "ingen kendte rettigheder" in haystack: return True, "No known rights", "no-known-rights", rights_text or "No known rights" return False, None, None, rights_text or None def parse_image_sets(root: ET.Element) -> list[dict[str, str | None]]: parents = [root] parents.extend(e for e in root.iter() if local_name(e.tag) == "relatedItem") out: list[dict[str, str | None]] = [] seen: set[str] = set() for parent in parents: identifiers = [child for child in list(parent) if local_name(child.tag) == "identifier"] by_label: dict[str, list[str]] = {} local_ids: list[str] = [] for identifier in identifiers: value = text_content(identifier) if not value: continue label = (identifier.get("displayLabel") or "").lower() ident_type = (identifier.get("type") or "").lower() if label: by_label.setdefault(label, []).append(value) elif ident_type == "local" or value.lower().endswith((".tif", ".jp2", ".jpg", ".jpeg", ".png")): local_ids.append(value) images = by_label.get("image", []) iiifs = by_label.get("iiif", []) thumbs = by_label.get("thumbnail", []) for idx, image_url in enumerate(images): normalized = image_url.replace("http://", "https://", 1) if normalized in seen: continue seen.add(normalized) out.append( { "image_url_original": normalized, "image_url_jpg_1600": normalize_iiif_image_url(normalized), "iiif_info_url": (iiifs[idx] if idx < len(iiifs) else (iiifs[0] if iiifs else None)), "thumbnail_url": (thumbs[idx] if idx < len(thumbs) else (thumbs[0] if thumbs else None)), "local_image_id": (local_ids[idx] if idx < len(local_ids) else (local_ids[0] if local_ids else None)), } ) return out def parse_mods_record(mods: ET.Element, raw_xml: str, edition: dict[str, str], matched_query: str) -> list[dict[str, Any]]: record_id = text_content(mods.find("./md:recordInfo/md:recordIdentifier", NS)) or "" if not record_id: return [] access_conditions = find_texts(mods, ".//md:accessCondition") accepted, license_name, license_bucket, license_text = classify_license(access_conditions, raw_xml) if not accepted: return [] image_sets = parse_image_sets(mods) if not image_sets: return [] title_da = [] title_en = [] title_other = [] for title_info in mods.findall("./md:titleInfo", NS): lang = title_info.get(XML_LANG) values = find_texts(title_info, "./md:title") if lang == "da": title_da.extend(values) elif lang == "en": title_en.extend(values) else: title_other.extend(values) title_da = dedupe_preserve(title_da) title_en = dedupe_preserve(title_en) title_other = dedupe_preserve(title_other) description_da: list[str] = [] description_en: list[str] = [] description_other: list[str] = [] for note in mods.findall(".//md:note", NS) + mods.findall(".//md:abstract", NS): value = text_content(note) if not value: continue lang = note.get(XML_LANG) if lang == "da": description_da.append(value) elif lang == "en": description_en.append(value) else: description_other.append(value) creators: list[str] = [] contributors: list[str] = [] persons: list[str] = [] for name in mods.findall(".//md:name", NS): name_value = " ".join(find_texts(name, "./md:namePart")) if not name_value: continue roles = [role.lower() for role in find_texts(name, ".//md:roleTerm")] if any(role in {"creator", "cre", "aut", "author"} for role in roles): creators.append(name_value) elif roles: contributors.append(name_value) if name.get("type") == "personal": persons.append(name_value) topics_da: list[str] = [] topics_en: list[str] = [] topics_other: list[str] = [] for topic in mods.findall(".//md:subject/md:topic", NS): value = text_content(topic) if not value: continue lang = topic.get(XML_LANG) if lang == "da": topics_da.append(value) elif lang == "en": topics_en.append(value) else: topics_other.append(value) breadcrumbs_da: list[str] = [] breadcrumbs_en: list[str] = [] for anchor in mods.findall(".//h:a", NS): value = text_content(anchor) if not value: continue if anchor.get(XML_LANG) == "en": breadcrumbs_en.append(value) else: breadcrumbs_da.append(value) object_id = object_id_from_record_id(record_id) preferred_title = (title_da or title_en or title_other or [None])[0] preferred_description = (description_da or description_en or description_other or [None])[0] preferred_text = ". ".join(part for part in [preferred_title, preferred_description] if part) if not preferred_text: preferred_text = preferred_title width = None height = None width_text = text_content(mods.find(".//mix:imageWidth", NS)) height_text = text_content(mods.find(".//mix:imageHeight", NS)) if width_text and width_text.isdigit(): width = int(width_text) if height_text and height_text.isdigit(): height = int(height_text) shelf_marks = find_texts(mods, ".//md:physicalLocation") local_ids = [ value for value in (text_content(e) for e in mods.findall(".//md:identifier", NS)) if value and value.lower().endswith((".tif", ".jp2", ".jpg", ".jpeg", ".png")) ] doms_guids = [ text_content(e) for e in mods.findall(".//md:identifier", NS) if (e.get("type") or "").lower() == "domsguid" and text_content(e) ] rows: list[dict[str, Any]] = [] for image_index, image in enumerate(image_sets): sample_id = f"{slugify(object_id)}-{image_index:02d}" row = { "sample_id": sample_id, "record_id": record_id, "object_id": object_id, "object_page_url": kbl_page_url(record_id), "source": "Royal Danish Library / Det Kgl. Bibliotek", "source_api": "KBL COP syndication API", "source_edition_id": edition["identifier"], "source_edition_title": edition["title"], "source_subset": edition.get("source_subset") or ("maps" if edition["identifier"].startswith("/maps/") else "billeder"), "source_kind": edition["source_kind"], "source_subject_id": edition.get("subject_id"), "source_subject_title": edition.get("subject_title"), "matched_license_query": matched_query, "license": license_name, "license_bucket": license_bucket, "license_text": license_text, "access_conditions": access_conditions, "is_strict_pd_or_ccby": license_bucket in {"public-domain", "cc-by", "cc-by-sa"}, "is_no_known_rights": license_bucket == "no-known-rights", "preferred_title": preferred_title, "preferred_description": preferred_description, "preferred_text": preferred_text, "preferred_language": "da" if title_da or description_da else ("en" if title_en or description_en else None), "title_da": title_da, "title_en": title_en, "title_other": title_other, "description_da": dedupe_preserve(description_da), "description_en": dedupe_preserve(description_en), "description_other": dedupe_preserve(description_other), "creators": dedupe_preserve(creators), "contributors": dedupe_preserve(contributors), "persons": dedupe_preserve(persons), "topics_da": dedupe_preserve(topics_da), "topics_en": dedupe_preserve(topics_en), "topics_other": dedupe_preserve(topics_other), "geographic_subjects": find_texts(mods, ".//md:subject/md:geographic"), "breadcrumbs_da": dedupe_preserve(breadcrumbs_da), "breadcrumbs_en": dedupe_preserve(breadcrumbs_en), "resource_types": find_texts(mods, ".//md:typeOfResource"), "forms": find_texts(mods, ".//md:physicalDescription/md:form"), "shelf_marks": shelf_marks, "local_ids": dedupe_preserve(local_ids), "doms_guids": dedupe_preserve([value for value in doms_guids if value]), "image_index": image_index, "image_url_original": image["image_url_original"], "image_url_jpg_1600": image["image_url_jpg_1600"], "iiif_info_url": image["iiif_info_url"], "thumbnail_url": image["thumbnail_url"], "local_image_id": image["local_image_id"], "width": width, "height": height, "raw_mods_xml": raw_xml, } rows.append(row) return rows def json_dumps(row: dict[str, Any]) -> str: return json.dumps(row, ensure_ascii=False, separators=(",", ":")) def read_jsonl(path: Path) -> list[dict[str, Any]]: if not path.exists(): return [] rows = [] with path.open("r", encoding="utf-8") as f: for line in f: if line.strip(): rows.append(json.loads(line)) return rows def viewer_features() -> Features: return Features( { "image": Image(decode=False), "sample_id": Value("string"), "record_id": Value("string"), "object_id": Value("string"), "object_page_url": Value("string"), "source": Value("string"), "source_api": Value("string"), "source_edition_id": Value("string"), "source_edition_title": Value("string"), "source_subset": Value("string"), "source_kind": Value("string"), "source_subject_id": Value("string"), "source_subject_title": Value("string"), "matched_license_query": Value("string"), "license": Value("string"), "license_bucket": Value("string"), "license_text": Value("string"), "access_conditions": Sequence(Value("string")), "is_strict_pd_or_ccby": Value("bool"), "is_no_known_rights": Value("bool"), "preferred_title": Value("string"), "preferred_description": Value("string"), "preferred_text": Value("string"), "preferred_language": Value("string"), "title_da": Sequence(Value("string")), "title_en": Sequence(Value("string")), "title_other": Sequence(Value("string")), "description_da": Sequence(Value("string")), "description_en": Sequence(Value("string")), "description_other": Sequence(Value("string")), "creators": Sequence(Value("string")), "contributors": Sequence(Value("string")), "persons": Sequence(Value("string")), "topics_da": Sequence(Value("string")), "topics_en": Sequence(Value("string")), "topics_other": Sequence(Value("string")), "geographic_subjects": Sequence(Value("string")), "breadcrumbs_da": Sequence(Value("string")), "breadcrumbs_en": Sequence(Value("string")), "resource_types": Sequence(Value("string")), "forms": Sequence(Value("string")), "shelf_marks": Sequence(Value("string")), "local_ids": Sequence(Value("string")), "doms_guids": Sequence(Value("string")), "image_index": Value("int32"), "image_url_original": Value("string"), "image_url_jpg_1600": Value("string"), "iiif_info_url": Value("string"), "thumbnail_url": Value("string"), "local_image_id": Value("string"), "width": Value("int32"), "height": Value("int32"), "download_status": Value("string"), "downloaded_image_format": Value("string"), "downloaded_width": Value("int32"), "downloaded_height": Value("int32"), "downloaded_bytes": Value("int64"), "webdataset_tar_path": Value("string"), "webdataset_member_jpg": Value("string"), "webdataset_member_json": Value("string"), "raw_mods_xml": Value("string"), } )