knowledge-enrichment/tools/scrape-calendar.py

198 lines
6.7 KiB
Python

# /// script
# requires-python = ">=3.12"
# dependencies = [
# "dump-things-pyclient @ https://hub.psychoinformatics.de/datalink/dump-things-pyclient.git",
# "things-enrichment-tools @ https://hub.psychoinformatics.de/orinoco/things-enrichment-tools.git",
# "icalendar",
# "rich",
# "rich-click",
# ]
# ///
import json
import logging
import urllib.request
from os import environ
import rich_click as click
from dump_things_pyclient.communicate import (
collection_read_record_with_pid,
collection_write_record,
)
from icalendar import Calendar
import things_enrichment_tools as tet
# example target format:
# https://hedgedoc.psychoinformatics.de/3cSouq0YSJ6m64_ArWpJEg?edit
urls = {
'juniorgroup': 'https://webmail.fz-juelich.de/owa/calendar/d61ec0ce8d704cb293df97fbb3c8fe23@fz-juelich.de/2e3e5a7baff44a3780cb2f872bef77b07381212461382934376/calendar.ics',
'funding': 'https://webmail.fz-juelich.de/owa/calendar/d61ec0ce8d704cb293df97fbb3c8fe23@fz-juelich.de/a7ad1dee32cf49749872136f3a9223191125633822045414026/calendar.ics',
'award': 'https://webmail.fz-juelich.de/owa/calendar/d61ec0ce8d704cb293df97fbb3c8fe23@fz-juelich.de/2f6c8a7e45e5416f89c22258bba6ae0114099503221118509202/calendar.ics',
}
competition_types = {
'funding': 'xyzrins:competition-types/4e49ac7d-d6da-4131-806b-6425491e26fd',
'award': 'xyzrins:competition-types/16e38ddd-6323-4fc7-abad-398609bf8541', # pid does not yet exist
'juniorgroup': 'xyzrins:competition-types/4e49ac7d-d6da-4131-806b-6425491e26fd',
}
class CalendarScraper:
def __init__(
self,
pool: str,
collection: str,
competition_type: str,
calendar_url: str,
) -> None:
self.pool = pool
self.collection = collection
self.comptetion_type = competition_type
self.calendar_url = calendar_url
# this list stores to-be-submitted records
self.to_submit = []
self.scriptpid = 'xyzrins:instruments/d3126ff5-623c-48af-ac48-4d921ef9b80d'
self.logger = logging.getLogger('CALENDAR-SCRAPER')
logging.basicConfig(level=logging.INFO)
def get_calendar(self) -> None:
if not self.calendar_url.startswith(('http:', 'https:')):
msg = "URL must start with 'http:' or 'https:'"
raise ValueError(msg)
with urllib.request.urlopen(self.calendar_url) as f: # noqa: S310
calsource = f.read().decode('utf-8')
self.cal = Calendar.from_ical(calsource)
def submit(self) -> None:
for record in self.to_submit:
self.logger.info(
'submitting record with pid %s to collection %s',
record['pid'],
self.collection,
)
try:
collection_write_record(
service_url=self.pool,
collection=self.collection,
class_name='XYZCompetition',
record=record,
format='json',
token=environ['DTC_TOKEN'],
)
except urllib.requests.exceptions.HTTPError:
self.logger.warning('SUBMISSION ERROR FOR RECORD: ')
self.logger.warning(json.dumps(record))
def _existing_or_new_record(self, pid: str) -> (dict, (dict | None)):
record = collection_read_record_with_pid(
service_url=self.pool,
collection=self.collection,
pid=pid,
token=environ['DTC_TOKEN'],
)
if record is None:
self.logger.info('New record: %s', pid)
record = {'pid': pid}
return record
def create_competitions(self) -> None:
self.get_calendar()
for event in self.cal.events:
pid = 'xyzrins:competition/' + event.get('UID').ical_value
self.assemble_record(pid, event)
self.submit()
def assemble_record(
self,
pid: str,
event: dict,
) -> dict | None:
"""Extract information from a calendar event and create a metadata
record from it."""
modified = set()
owner_props = {'source_id': self.calendar_url, 'owner_id': self.scriptpid}
record = self._existing_or_new_record(pid)
# title
modified.add(
tet.update_data_property(
record,
predicate='dcterms:title',
topical_slot='title',
value=event.get('SUMMARY').ical_value,
**owner_props,
)
)
# description
desc = event.get('DESCRIPTION').ical_value.replace('\n', ' ')
if 'Please note' in desc:
desc = desc.split('Please note')[0]
modified.add(
tet.update_data_property(
record,
predicate='dcterms:description',
topical_slot='description',
value=desc,
**owner_props,
)
)
# deadline
modified.add(
tet.update_data_property(
record,
predicate='dcterms:date',
topical_slot='application_deadline',
value=event.get('DTSTART').td.isoformat(),
**owner_props,
)
)
# kind
modified.add(
tet.update_data_property(
record,
collection_slot='characterized_by',
predicate='dcterms:type',
value_key='object',
topical_slot='kind',
value=competition_types[self.comptetion_type],
**owner_props,
)
)
if True not in modified:
self.logger.debug('No change for existing record with PID %s', pid)
return
self.to_submit.append(record)
return
@click.command()
@click.option('--dtc-api-url', '-a', default='https://pool.psychoinformatics.de/api')
@click.option('--dtc-collection', '-c', default='public')
def main(
dtc_api_url: str = 'https://pool.psychoinformatics.de/api',
dtc_collection: str = 'public',
) -> None:
"""
Scrape the outlook funding calendars of the FZJ and write events as
Competition records into the knowledge pool at --dtc-api-url, into the
collection determined by --dtc-collection.
"""
if environ.get('DTC_TOKEN', None) is None:
msg = 'DTC_TOKEN required in environment! Aborting.'
raise OSError(msg)
for competition_type, url in urls.items():
scraper = CalendarScraper(
pool=dtc_api_url,
collection=dtc_collection,
competition_type=competition_type,
calendar_url=url,
)
scraper.logger.info('scraping for %s', competition_type)
scraper.create_competitions()
if __name__ == '__main__':
main()