| |
| """ |
| Download UD metadata for the different releases from the lindat clarin-dspace |
| repository into `./etc/`: |
| - BibTeX "Howto Cite" |
| (use the item's own data from the webpage) |
| - dc.description |
| (use the clarin-dspace API to retrieve the item's metadata) |
| |
| We assume a clarin-dspace infrastructure with: |
| - ".../repository/server/api/core/refbox/citations?type=bibtex&handle=" |
| returning a bibtex entry for the given hdl |
| - ".../repository/server/api/core/items/" as the API endpoint (core/items) |
| """ |
|
|
| import json |
| import re |
| import argparse |
| import logging |
| from pathlib import Path |
| from urllib.error import URLError |
| from urllib.request import urlopen |
| from urllib.parse import urlparse |
|
|
| |
| citation_url_prefix = "https://lindat.mff.cuni.cz/repository/server/api/core/refbox/citations?type=bibtex&handle=" |
| description_url_prefix = "https://lindat.mff.cuni.cz/repository/server/api/core/items/" |
| handle_url_prefix = "http://hdl.handle.net/" |
| handle_redirect_url_prefix = "https://lindat.mff.cuni.cz/repository/items/" |
|
|
| TOOLS_DIR = Path(__file__).resolve().parent |
| OUTPUT_DIR = TOOLS_DIR / "etc" |
| citation_outfile_name = "citation-{rev}" |
| description_outfile_name = "description-{rev}" |
| release_handle_map_file = OUTPUT_DIR / "ud_release_handles.tsv" |
|
|
| def load_release_handles(path: Path) -> dict[str, str]: |
| """ |
| Load the UD-version -> LINDAT handle mapping from a TSV file. |
| """ |
| mapping: dict[str, str] = {} |
| with path.open("r", encoding="utf-8") as fh: |
| for lineno, raw_line in enumerate(fh, start=1): |
| line = raw_line.strip() |
| if not line or line.startswith("#"): |
| continue |
| fields = line.split() |
| if len(fields) != 2: |
| raise ValueError(f"Invalid mapping format at {path}:{lineno}: {raw_line.rstrip()}") |
| rev, handle = fields |
| mapping[rev] = handle |
| return mapping |
|
|
| |
| parser = argparse.ArgumentParser(description=__doc__, |
| formatter_class=argparse.RawDescriptionHelpFormatter) |
| parser.add_argument('-o', '--override', action='store_true', |
| help='override output file if it already exists') |
| parser.add_argument('--ud-ver', dest='ud_ver', |
| help='only fetch one UD version (e.g. 2.17)') |
| |
| parser.add_argument('-r', '--rev', dest='ud_ver', help=argparse.SUPPRESS) |
| parser.add_argument('-v', '--verbose', action='count', default=0, |
| help='increase verbosity level') |
| args = parser.parse_args() |
|
|
| |
| logging.basicConfig( |
| level = max(logging.DEBUG, logging.INFO - args.verbose * 10), |
| format='%(asctime)s [%(levelname)s] %(message)s', |
| datefmt='%Y-%m-%d %H:%M:%S' |
| ) |
|
|
| |
| try: |
| url_postfixes = load_release_handles(release_handle_map_file) |
| except (OSError, ValueError) as e: |
| raise SystemExit(f"Failed to load release-handle mapping from {release_handle_map_file}: {e}") |
|
|
| if args.ud_ver: |
| if args.ud_ver not in url_postfixes: |
| known = ", ".join(sorted(url_postfixes.keys())) |
| raise SystemExit(f"Unknown UD version '{args.ud_ver}'. Known versions: {known}") |
| url_postfixes = {args.ud_ver: url_postfixes[args.ud_ver]} |
|
|
| OUTPUT_DIR.mkdir(parents=True, exist_ok=True) |
|
|
| |
| for rev,handle in url_postfixes.items(): |
|
|
| try: |
| |
| citation_url = citation_url_prefix + handle |
| logging.debug(f"Using Citation URL: {citation_url}") |
|
|
| |
| with urlopen(citation_url) as response: |
|
|
| |
| data = json.loads(response.read().decode()) |
|
|
| |
| metadata = data.get("metadata") |
|
|
| |
| if metadata: |
| |
| |
| metadata = "\n".join([re.sub('^( )+', ' ', line) for line in |
| metadata.split("\n")]) |
|
|
| |
| output_fn = OUTPUT_DIR / citation_outfile_name.format(rev=rev) |
| if args.override or not output_fn.exists(): |
| with output_fn.open("w") as fh: |
| fh.write(metadata + "\n") |
| logging.info(f"Successfully downloaded citation from {citation_url} and written to {output_fn}.") |
| else: |
| logging.info(f"Output {output_fn} already exists: Not overriding.") |
|
|
|
|
| |
| handle_url = handle_url_prefix + handle |
| logging.debug(f"Using handle URL: {handle_url}") |
| |
| with urlopen(handle_url) as response: |
| if response.url.startswith(handle_redirect_url_prefix): |
| itemid = (urlparse(response.url)).path.rsplit("/", 1)[-1] |
|
|
| description_url = description_url_prefix + itemid |
| with urlopen(description_url) as response: |
| data = json.loads(response.read().decode()) |
| description = data["metadata"]["dc.description"][0]["value"] |
| if description: |
|
|
| |
| output_fn = OUTPUT_DIR / description_outfile_name.format(rev=rev) |
| if args.override or not output_fn.exists(): |
| with output_fn.open("w") as fh: |
| fh.write(description+ "\n") |
| logging.info(f"Successfully downloaded description from {description_url} and written to {output_fn}.") |
| else: |
| logging.info(f"Output {output_fn} already exists: Not overriding.") |
|
|
| except URLError as e: |
| logging.error(f"Error downloading: {e}") |
| except json.JSONDecodeError as e: |
| logging.error(f"Error decoding JSON: {e}") |
|
|