knowledge-enrichment/tools/scrape-juser.py
2026-08-25 14:53:20 +02:00

741 lines
27 KiB
Python

# /// script
# requires-python = ">=3.12"
# dependencies = [
# "defusedxml",
# "dump-things-pyclient @ https://hub.psychoinformatics.de/datalink/dump-things-pyclient.git",
# "things-enrichment-tools @ https://hub.psychoinformatics.de/orinoco/things-enrichment-tools.git",
# "pymarc",
# "rich",
# "rich-click",
# ]
# ///
"""
Using a local xml file with MARCXML publication data from JUSER, this script
creates and submits publication records to a given pool.
Usage:
1) Download xml data with one of JUSERs generated search URLs
(see https://juser.fz-juelich.de/search_generator.py)
> mkdir .cache
> curl 'https://juser.fz-juelich.de/PubExporter.py?p=cid%3A%22I%3A%28DE-Juel1%29INM-7-20090406%22+AND+pub%3A%222026%22&sf=author&so=d&rg=&of=xm' > .cache/juser-pubs.xml
2) Cache Person and Publication records from your pool
> dtc get-records $DUMPTHINGS_APIURL \
public -C XYZPublication > .cache/Publications.jsonl
> dtc get-records $DUMPTHINGS_APIURL \
public -C XYZPerson > .cache/Person.jsonl
> dtc get-records $DUMPTHINGS_APIURL \
protected -C XYZPerson >> .cache/Person.jsonl
3) Invoke the script
> uv run tools/scrape-juser.py \
--file .cache/juser-pubs.xml \
--persons .cache/Person.jsonl \
--publications .cache/Publications.jsonl
"""
import json
import logging
import uuid
from collections.abc import Callable
from os import environ
from pathlib import Path
from typing import Any
from urllib import parse
from xml.etree.ElementTree import ParseError as XMLParseError
import click
import requests
from defusedxml.ElementTree import (
fromstring as xmlfromstring,
)
from dump_things_pyclient.communicate import collection_write_record
from pymarc import parse_xml_to_array
from requests import Session
import things_enrichment_tools as tet
def juser_session(
url: str = 'https://juser.fz-juelich.de/youraccount/login',
):
"""Create a Session object in order to have a persisting session token
for authentication. This is required for Person searches."""
data = {
'login_method': 'FZJ eMail-Account',
'p_un': environ.get('JUSER_USER'),
'p_pw': environ.get('JUSER_PW'),
'action': 'login',
}
s = Session()
# required to solve challenge
s.cookies.set('APP_INIT', '1')
response = s.post(url, data=data)
response.raise_for_status()
return s
def _lookup(record, field1: str, field2: str) -> str | None:
"""Helper function to look up metadata without running into KeyErrors"""
parentfield = record.get(field1, None)
if parentfield is not None:
value = parentfield.get(field2, None)
if value is not None:
return value
return None
class JuserScraper:
def __init__(self, pool: str, collection: str, xml: str, persons, pubs) -> None:
self.pool = pool
self.collection = collection
self.xml = Path(xml)
# caches of dumpthings records
self.persons = map_record_to_feature(process_orcid, persons)
self.pubs = map_record_to_feature(process_doi, pubs)
# cache of jul_id to ORCID associations
self.jul_ids = {}
# this list stores to-be-submitted records
self.to_submit_public = []
self.to_submit_protected = []
# establish a session to Juser
self.session = juser_session()
# potentially make this a parameter
self.scriptpid = 'xyzrins:instruments/d3126ff5-623c-48af-ac48-4d921ef9b80d'
self.logger = logging.getLogger('JUSER-SCRAPER')
logging.basicConfig(level=logging.INFO)
def create_records(self) -> None:
records = parse_xml_to_array(self.xml)
self.logger.info('Found %s publication records', len(records))
# Loop over all records
for r in records:
self.retrieve_metadata(r)
def submit_records(
self,
records: list,
collection: str,
class_name: str,
) -> None:
# finally, submit:
for record in records:
self.logger.info(
'submitting record with pid %s to collection %s',
record['pid'],
collection,
)
try:
collection_write_record(
service_url=self.pool,
collection=collection,
class_name=class_name,
record=record,
format='json',
token=environ['DTC_TOKEN'],
)
except requests.exceptions.HTTPError:
self.logger.info('SUBMISSION ERROR FOR RECORD: ')
self.logger.info(json.dumps(record))
def _get_attribution(
self,
r,
) -> list:
authors = r.get_fields('700')
new_attributions = []
for author in authors:
orcid = None
jul_id = None
# if the author haus an FZJ affiliation, get their info. We can most
# reliably look up Orcid based on Julich ID -- external authors
# often are only mentioned by name
if '(DE-Juel1)' in author.subfields[1].value:
jul_id = author.subfields[1].value
display_label = author.subfields[0].value
orcid, record_id = self._look_up_orcid(jul_id)
self.logger.debug(
'Found author %s under ID %s with orcid %s: %s',
display_label,
jul_id,
orcid,
record_id,
)
mainid = orcid
if orcid is None:
if not jul_id:
# stop when the author has neither orcid nor jul_id
continue
# we can make a second attempt with a Julich-issued ID
mainid = self.persons.get(jul_id, None)
if not mainid:
continue
# either get the pid of the preexisting record or build new pid
pid = self.persons.get(mainid, {}).get(
'pid', 'xyzrins:persons/' + str(uuid.uuid4())
)
owner_props = {'source_id': record_id, 'owner_id': self.scriptpid}
# potentially create or update the person record
self._person_record(
pid=pid,
mainid=mainid,
orcid=orcid,
jul_id=jul_id,
display_label=display_label,
owner_props=owner_props,
)
# create the author attribution:
new_attributions.extend([{'object': pid}])
return new_attributions
def _person_record(
self,
pid,
mainid,
orcid,
jul_id,
display_label,
owner_props,
) -> None:
"""for an existing person record, check ORCID or jul_id can be added"""
modified = set()
if mainid not in self.persons:
self.logger.info('CREATING NEW PERSON RECORD FOR %s', display_label)
record = {'pid': pid, 'display_label': display_label}
else:
record = self.persons.get(mainid)
ids = [
{'creator': 'https://w3id.org/isil/DE-Juel1', 'notation': jul_id},
{
'schema_type': 'xyzri:ORCID',
'creator': 'ror:04fa4r544',
'notation': orcid,
},
]
modified.add(
tet.update_multivalued_object_property(
record, slot='identifiers', values=ids, **owner_props
)
)
if True in modified:
# update internal cache and store for submission
self.persons[mainid] = record
self.to_submit_protected.append(record)
def _get_influence(
self,
r,
) -> list:
influences = []
all_funding = r.get_fields('536')
for funding in all_funding:
fund = funding['0']
# this fund may be a PoF association or a grant
fund_rec = map_grant_to_pid.get(fund)
if fund_rec is not None:
influences.extend(
[
{
'object': fund_rec['pid'],
'roles': ['FRAPO:Funding'],
'ended': {
'at_time': fund_rec['end'],
'schema_type': 'dlthings:End',
},
'started': {
'at_time': fund_rec['start'],
'schema_type': 'dlthings:Start',
},
}
]
)
return influences
def _get_funding(
self,
r,
annotations,
) -> list | None:
all_funding = r.get_fields('536')
funding_ack = []
for funding in all_funding:
fund = funding['0']
# this fund may be a PoF association or a grant
fund_rec = map_grant_to_pid.get(fund)
if fund_rec is not None:
funding_ack.append(
{
'object': fund_rec['pid'],
'roles': ['FRAPO:Funding'],
'ended': {
'at_time': fund_rec['end'],
'schema_type': 'dlthings:End',
},
'started': {
'at_time': fund_rec['start'],
'schema_type': 'dlthings:Start',
},
'annotations': annotations,
}
)
return funding_ack
def retrieve_metadata(
self,
r,
):
"""For a given MARCXML publication record from Juser, check if a
publication with this DOI is already in the pool. If a record already
exists, check if it needs amendments. If a record does not exist,
assemble a publication metadata record from scratch"""
modified = set()
# first, get the DOI and check if the publication already exists
doi = self._get_doi(r)
if doi is None:
return
# record of the juser ID, for owner provenance
juser_id = r.fields[0].data
owner_props = {
'source_id': f'https://juser.fz-juelich.de/record/{juser_id}',
'owner_id': self.scriptpid,
}
if doi in self.pubs:
record = self.pubs[doi]
self.logger.info('CHECKING EXISTING PUBLICATION WITH DOI %s', doi)
# because JUSER is stupid:
elif doi.lower() in self.pubs:
record = self.pubs[doi.lower()]
self.logger.info('CHECKING EXISTING PUBLICATION WITH DOI %s', doi)
else:
self.logger.info('CREATING NEW PUBLICATION FOR DOI %s', doi)
record = {'pid': 'xyzrins:publications/' + str(uuid.uuid4())}
tet.update_multivalued_object_property(
record,
slot='identifiers',
values=[{'schema_type': 'dlthings:DOI', 'notation': doi}],
**owner_props,
)
# title
modified.add(
tet.update_data_property(
record,
predicate='dcterms:title',
topical_slot='title',
value=_lookup(r, '245', 'a'),
**owner_props,
)
)
# abstract
abstract = _lookup(r, '520', 'a')
if abstract is not None:
modified.add(
tet.update_data_property(
record,
predicate='dcterms:abstract',
topical_slot='description',
value=abstract,
**owner_props,
)
)
# kind
kind = map_content_to_bibitem.get(_lookup(r, '336', 'a'))
if kind is not None:
modified.add(
tet.update_data_property(
record,
collection_slot='characterized_by',
predicate='dcterms:type',
value_key='object',
topical_slot='kind',
value=kind,
**owner_props,
)
)
# pof and publication generation
pof_proj_generations = [
{'object': map_pof_to_pid[funding['0']]}
for funding in r.get_fields('536')
if funding['0'] in map_pof_to_pid
]
generations = [*pof_proj_generations, *self.get_publication_generations(r)]
modified.add(
tet.update_multivalued_object_property(
record, slot='generated_by', values=generations, **owner_props
)
)
# attributions
attributed_to = self._get_attribution(r)
modified.add(
tet.update_multivalued_object_property(
record, slot='attributed_to', values=attributed_to, **owner_props
)
)
# influences
influenced_by = self._get_influence(r)
modified.add(
tet.update_multivalued_object_property(
record, slot='influenced_by', values=influenced_by, **owner_props
)
)
if True in modified:
# publication records can be public
self.logger.info('FOUND AN UPDATE FOR %s', doi)
self.to_submit_public.append(record)
return
def get_publication_generations(
self,
r,
) -> list[dict[str, Any]]:
date = _lookup(r, '773', 'y')
location = self._get_periodical(r)
if date is None and location is None:
return []
gen = {'object': 'obo:IAO_0000444'}
if location:
gen['at_location'] = f'ISSN:{location}'
if date:
gen['at_time'] = str(date)
return [gen]
def _get_doi(self, r) -> str | None:
doi = None
# check if field 024 exists
test = _lookup(r, '024', 'a')
if test and r['024'].subfields[1].value == 'doi':
doi = r['024']['a']
return doi
def _get_periodical(self, r) -> str | None:
"""Obtain the ISSN of a publication venue"""
# The ZB identifies periodicals via an internal ID, e.g.,
# 'PERI:(DE-600)2808093-2'We can look up the ISSN
# for an ID in their periodicals collection:
# https://juser.fz-juelich.de/collection/Periodicals?ln=en
peri = _lookup(r, '773', '0')
if peri is None:
return None
peri_id = parse.quote_plus(peri)
url = f'https://juser.fz-juelich.de/search?ln=en&cc=Periodicals&p={peri_id}&f=&action_search=Search&c=Periodicals&c=&sf=&so=d&rm=&rg=10&sc=1&of=xm'
x = self._look_up_juser_info(url, attempts=3)
# look up ISSN in the XML above. XML is a mess.
try:
issn = x.findall(".//*[@tag='022']")[0][1].text
except IndexError:
issn = None
return issn
def _look_up_juser_info(self, url: str, attempts: int = 3):
# The retrieval of search results often glitches when ran in short
# succession, so we safeguard and retry
lookup = False
attempt = 0
while not lookup and attempt < attempts:
try:
res = self.session.get(url)
attempt += 1
x = xmlfromstring(res.content.decode())
except XMLParseError:
self.logger.info('JUSER GLITCH, RETRYING...')
continue
lookup = True
return x
def _look_up_orcid(
self,
jul_id: str,
) -> (str, str):
if jul_id in self.jul_ids:
# this ID is already known, don't query again
return self.jul_ids[jul_id], None
# URL encode the ID
id_ = parse.quote_plus(jul_id)
url = f'https://juser.fz-juelich.de/search?ln=en&p={id_}&f=&action_search=Search&c=People&sf=author&so=d&rm=&rg=10&sc=0&of=xm'
x = self._look_up_juser_info(url, attempts=3)
# look up ORCID in the XML above. XML is a mess.
try:
orcid = {
e[0].text.casefold(): e[1].text for e in x.findall(".//*[@tag='024']")
}['orcid']
# add to cache
self.jul_ids[jul_id] = orcid
except KeyError:
orcid = None
record_id = next(
(e.text for e in x.findall(".//*[@tag='001']")),
None,
)
record_source = (
None
if record_id is None
else f'https://juser.fz-juelich.de/record/{record_id}'
)
return orcid, record_source
def map_record_to_feature(feature: Callable, records: list[dict]) -> dict[Any, dict]:
"""Create a mapping of records to a specific feature (DOI or ORCIDs)"""
my_map = {}
for record in records:
if (feat := feature(record)) is not None:
my_map[feat] = record
return my_map
# TODO: taken from enrich-via-doi.py -- factor out and import!
def process_doi(paper: dict) -> str | None:
"""Return a DOI from identifiers"""
for identifier in paper.get('identifiers', []):
if (
pid_of(identifier.get('creator')) == 'ror:01fyxcz70'
or identifier.get('schema_type') == 'dlthings:DOI'
):
return identifier.get('notation')
return
def pid_of(x: str | dict) -> str:
"""Return a PID of an object, inlined or not
A shortcut - makes a pid string or an inlined dict (where pid is a
property) equivalent. Does not do further validation, but it could
be added here.
"""
return x.get('pid', '') if isinstance(x, dict) else x
def _get_pof(r) -> list:
all_funding = r.get_fields('536')
# for XYZPublication in Research Information, generation is multivalued
pof_gen = []
for funding in all_funding:
fund = funding['0']
# this fund may be a PoF association or a grant
pof_pid = map_pof_to_pid.get(fund)
if pof_pid is not None:
pof_gen.append({'object': pof_pid})
return pof_gen
def process_orcid(person: dict) -> str | None:
"""Return an ORCID from identifiers. If no ORCID is found, try a ZB issued
ID."""
for identifier in person.get('identifiers', []):
# this is a deviation from enrich-via-doi, which filtered based on
# '("creator")) == "ror:04fa4r544"' -- in the psyinf pool, only a
# fraction of identifiers have this creator annotation
if pid_of(identifier.get('schema_type')) == 'xyzri:ORCID':
return identifier.get('notation')
# if we do not find an ORCID, we make another attempt based on ZB-issued ID
for identifier in person.get('identifiers', []):
if (
pid_of(identifier.get('schema_type')) == 'dlthings:Identifier'
and pid_of(identifier.get('creator')) == 'https://w3id.org/isil/DE-Juel1'
):
return identifier.get('notation')
return
map_pof_to_pid = {
'G:(DE-HGF)POF4-5251': 'xyzrins:projects/45e542dd-2d2a-41d0-8399-90f2fde72a21',
'G:(DE-HGF)POF4-5252': 'xyzrins:projects/858d0ddb-3c51-4cea-a0e5-a73224b59ae5',
'G:(DE-HGF)POF4-5253': 'xyzrins:projects/64777d99-26f6-441c-9849-ba8018571de8',
'G:(DE-HGF)POF4-5254': 'xyzrins:projects/5340dd43-6ef0-4cf8-a936-67c2a9f3a725',
'G:(DE-HGF)POF4-5255': 'xyzrins:projects/a3f0a9e0-c945-4e04-a698-be426a9ac075',
}
map_grant_to_pid = {
'G:(EU-Grant)101147319': {
'pid': 'xyzrins:grants/ebrains-2.0',
'start': '2024-01-01',
'end': '2026-12-01',
},
'G:(GEPRIS)552122525': { # SFB B06
'pid': 'https://concepts.datalad.org/s/demo-research-information/ns/grants/143b2417-20a6-45d1-8140-dfddceb61749',
'start': '2025-01-01',
'end': '2028-12-31',
},
'G:(GEPRIS)458705014': { # SFB Z03
'pid': 'https://concepts.datalad.org/s/demo-research-information/ns/grants/1325c9f4-279a-42d1-ba37-ed5577965620',
'start': '2021-01-01',
'end': '2028-12-31',
},
'G:(GEPRIS)458684554': { # SFB C05
'pid': 'https://concepts.datalad.org/s/demo-research-information/ns/grants/3977dc9e-59e9-4ff2-bcbf-5bcb8f1c5c2d',
'start': '2021-01-01',
'end': '2028-12-31',
},
'G:(GEPRIS)458640473': { # SFB B05
'pid': 'https://concepts.datalad.org/s/demo-research-information/ns/grants/66cbbef2-5fd4-42c6-8348-cb74af435b75',
'start': '2021-01-01',
'end': '2028-12-31',
},
'G:(DE-HGF)InterLabs-0015': { # HIBALL
'pid': 'https://concepts.datalad.org/s/demo-research-information/ns/grants/391de57c-8040-4cf7-a515-a6791b9a0c89',
'start': '2020-04-01',
'end': '2025-03-31',
},
'G:(EU-Grant)945539': { # HBP SGA3
'pid': 'https://concepts.datalad.org/s/demo-research-information/ns/grants/hbp-sga3',
'start': '2020-04-01',
'end': '2023-09-30',
},
'G:(EU-Grant)604102': { # HBP
'pid': 'https://concepts.datalad.org/s/demo-research-information/ns/grants/ff4d1947-f1ad-4e9f-88fc-57af7b7cfc85',
'start': '2013-10-01',
'end': '2017-02-28',
},
'G:(GEPRIS)431549029': { # SFB 1451 insgesamt
'pid': 'https://concepts.datalad.org/s/demo-research-information/ns/grants/sfb1451',
'start': '2021-01-01',
'end': '2028-12-31',
},
'G:(DE-Juel1)JL SMHB-2021-2027': { # JL SMHB
'pid': 'https://concepts.datalad.org/s/demo-research-information/ns/grants/2b40e9ef-d9d2-42f8-a502-2e6efa86a1f7',
'start': '2021-01-01',
'end': '2027-12-31',
},
'G:(GEPRIS)524408221': { # Mikrostrukturelle Entwicklung des Gehirns
'pid': 'https://concepts.datalad.org/s/demo-research-information/ns/grants/003e63be-a64b-4d72-a912-392b40710a48',
'start': '2024-10-01',
'end': '2027-09-30',
},
'G:(EU-Grant)826421': { # VirtualBrainCloud
'pid': 'https://concepts.datalad.org/s/demo-research-information/ns/grants/4919df79-bb48-443a-b74d-3eb83e466187',
'start': '2018-12-01',
'end': '2023-05-31',
},
'G:(MKW NRW)KP22-106A': { # ABCD-J
'pid': 'https://concepts.datalad.org/s/demo-research-information/ns/grants/mkw-abcd-j',
'start': '2023-05-01',
'end': '2027-04-30',
},
'G:(DE-HGF)ZT-I-P-4-062': { # BrainShapes
'pid': 'https://concepts.datalad.org/s/demo-research-information/ns/grants/a9fab6a8-7854-41e8-869f-0cec467875c2',
'start': '2024-02-01',
'end': '2027-01-31',
},
'G:(GEPRIS)PA 3634/4-1': { # PETPartTI
'pid': 'https://concepts.datalad.org/s/demo-research-information/ns/grants/f83f2dce-0de3-4660-8b75-bb4bc3ca6977',
'start': '2024-03-01',
'end': '2027-02-28',
},
'G:(DE-Juel1)BMBF-01GP2310A': { # RHUNE
'pid': 'https://concepts.datalad.org/s/demo-research-information/ns/grants/927d6d5b-09f1-4432-97c2-ced899a19bff',
'start': '2024-03-01',
'end': '2028-02-29',
},
'G:(DE-Juel1)BMBF-16SV9391': { # VINNIE
'pid': 'https://concepts.datalad.org/s/demo-research-information/ns/grants/6f185c4c-8fc6-4e37-9c1d-34228c4281e1',
'start': '2025-01-01',
'end': '2027-12-31',
},
'G:(DE-HGF)ZT-I-PF-5-231': { # NorMImag
'pid': 'https://concepts.datalad.org/s/demo-research-information/ns/grants/b705c302-2ec3-45a6-ab0d-a82f439a85f5',
'start': '2025-09-01',
'end': '2027-08-31',
},
'G:(DE-Juel1)BMBF-01GP2505B': { # NAWiStem3D
'pid': 'https://concepts.datalad.org/s/demo-research-information/ns/grants/f8bc2700-ada4-4f4d-aae1-886c43026ba7',
'start': '2026-03-01',
'end': '2029-02-28',
},
'G:(DE-Juel1)BMBF-01GP2420': { # BRAINTREE
'pid': 'https://concepts.datalad.org/s/demo-research-information/ns/grants/9a16e66c-c8c0-4321-9932-5f1e68a8a1d9',
'start': '2024-05-01',
'end': '2027-04-30',
},
'G:(DE-Juel1)BMFTR-16SV9601': { # I-CHECK-HEART
'pid': 'https://concepts.datalad.org/s/demo-research-information/ns/grants/9b9d37cb-30fa-4e8c-9308-0afa4a4a2a50',
'start': '2026-03-01',
'end': '2029-02-28',
},
'G:(DE-Juel1)BMFTR-16SV9520': { # HELIA
'pid': 'https://concepts.datalad.org/s/demo-research-information/ns/grants/a1a89bb1-5596-439a-ac65-903494549bd2',
'start': '2025-10-01 ',
'end': '2028-09-30',
},
'G:(GEPRIS)574519660': {
# Dynamics of immune, glial and neuronal network interaction
'pid': 'https://concepts.datalad.org/s/demo-research-information/ns/grants/0f4eee2d-aeb2-44be-84da-7bd205f376b0',
'start': '2026-10-01',
'end': '2030-06-30',
},
}
map_content_to_bibitem = {
'article': 'bibo:AcademicArticle',
'lecture': 'fabio:Presentation',
'Conference Paper': 'bibo:Proceedings',
'CONFERENCE_PAPER': 'bibo:Proceedings',
'PATENT': 'bibo:Patent',
'BOOK_CHAPTER': 'bibo:Chapter',
'Preprint': 'bibo:Manuscript',
'Output Types/Dissertation': 'bibo:Thesis',
}
@click.command()
@click.option('--dtc-api-url', '-a', default='https://pool.psychoinformatics.de/api')
@click.option('--dtc-collection', '-c', default='public')
@click.option('--file', '-f')
@click.option('--persons', type=click.File('rb'), default='.cache/Person.jsonl')
@click.option(
'--publications', type=click.File('rb'), default='.cache/Publications.jsonl'
)
@click.option(
'--submit',
type=click.Choice(['XYZPerson', 'XYZPublication', 'both']),
default='both',
)
def main(
file: str,
dtc_api_url: str,
dtc_collection: str,
submit: str,
persons,
publications,
) -> None:
"""
Given an XML file with MARCXML publication data provided as --file,
parse publication records and submit them to a pool at --dtc-api-url
as Publication records, into the collection determined by
--dtc-collection. Set the environment variables JUSER_PW and JUSER_USER
to your Juser Login credentials.
"""
if environ.get('DTC_TOKEN', None) is None:
msg = 'DTC_TOKEN required in environment! Aborting.'
raise OSError(msg)
if environ.get('JUSER_PW', None) is None or environ.get('JUSER_USER', None) is None:
msg = 'JUSER_PW and JUSER_USER required in environment! Aborting.'
raise OSError(msg)
all_people = [json.loads(line) for line in persons] if persons is not None else []
all_pubs = (
[json.loads(line) for line in publications] if persons is not None else []
)
js = JuserScraper(
pool=dtc_api_url,
collection=dtc_collection,
xml=file,
persons=all_people,
pubs=all_pubs,
)
js.create_records()
if submit in ['both', 'XYZPublication']:
js.submit_records(
js.to_submit_public, collection='public', class_name='XYZPublication'
)
if submit in ['both', 'XYZPerson']:
js.submit_records(
js.to_submit_protected, collection='protected', class_name='XYZPerson'
)
if __name__ == '__main__':
main()