view graphconvert.py @ 83:7f50e5bb30f5

ide
author drewp@bigasterisk.com
date Sat, 07 Sep 2024 16:12:15 -0700
parents f2dd88b9964c
children f75b3a109b66
line wrap: on
line source

from dateutil.tz import tzlocal
from rdflib import RDF, RDFS, ConjunctiveGraph, Literal, Namespace, URIRef

from localtypes import Conf, feedFromCalId

EV = Namespace("http://bigasterisk.com/event#")


def asGraph(conf: Conf, cals, events, extraClasses=[], ctxUri: URIRef = EV['gcalendar']):
    ctx = ConjunctiveGraph(identifier=ctxUri)
    graph = ConjunctiveGraph()
    graph.namespace_manager.bind('ev', EV)

    for doc in cals:
        feed = URIRef(feedFromCalId(conf, doc['_id']))
        graph.add((feed, RDF.type, EV['CalendarFeed'], ctx))
        if doc['summary']:
            graph.add((feed, RDFS.label, Literal(doc['summary'].strip()), ctx))
        if doc['description']:
            graph.add((feed, EV['description'], Literal(doc['description'].strip()), ctx))

    for ev in events:
        uri = URIRef(ev.get('uri', ev.get('_id')))
        if uri is None:
            raise ValueError(f"{ev=} had no event uri")

        def add(p: URIRef, o: URIRef | Literal):
            return graph.add((uri, p, o, ctx))

        add(RDF.type, EV['Event'])
        for cls in extraClasses:
            add(RDF.type, cls)
        add(EV['title'], Literal(ev['title']))
        add(EV['start'], Literal(ev['start']))
        add(EV['startDate'], Literal(ev['startDate']))
        add(EV['end'], Literal(ev['end']))
        add(EV['feed'], URIRef(ev['feed']))
        # graph.add((feed, RDFS.label, Literal(ev['feedTitle'])))
        if 'htmlLink' in ev:
            add(EV['htmlLink'], URIRef(ev['htmlLink']))
    return graph