Select Git revision
Eliott Sammier authored
common.py 2.98 KiB
from sys import stderr
from typing import Any, Optional
from rdflib import RDFS, Graph, Literal, URIRef
from rdflib import Namespace
from os import path, environ
def env_path_or_rel_default(env_var: str, default: str) -> str:
"""Get a path stored in an environment variable, using a default path
relative to this file if the variable is unset
:param env_var: The name of the variable
:param default: A *relative* path to use as default
"""
return path.realpath(environ.get(env_var) or path.join(MODULE_DIR, default))
# Path constants ###############################################################
MODULE_DIR = path.dirname(path.realpath(__file__))
"""Absolute path of this module's directory"""
MACAO_ROOT = env_path_or_rel_default("MACAO_ROOT", "../../..")
"""Path to the Macao root directory"""
SOURCE_DIR = env_path_or_rel_default("SOURCES_DIR", "../../../Basilisk/MACAO/macao_12")
"""Path to the Macao source directory (i.e. the one with the manifest)"""
RESULT_DIR = env_path_or_rel_default("RESULTS_DIR", "../result")
"""Path to the output directory"""
RESULT_FILE = env_path_or_rel_default("RESULT_FILE", "../result/macao_content.ttl")
"""Path to the Turtle output file"""
SCHEMA_FILE = env_path_or_rel_default("SCHEMA_FILE", "../macao_schema.ttl")
"""Path to the schema file"""
NS = Namespace("http://www.semanticweb.org/eliott/ontologies/2024/4/macao/")
"""The rdflib base Namespace for our ontology"""
# Utility functions ############################################################
def eprint(*args, **kwargs):
"""Just like `print()`, but to standard error instead of standard output"""
print(*args, file=stderr, **kwargs)
def insert_grow(l: list, index: int, value: Any, fill_value: Optional[Any] = None):
"""Insert at a given position in a list, growing it if necessary
:param l: list
:param index: The position where the value is inserted
:param value: The value to insert
:param fill_value: The value used for elements created automatically when growing, defaults to None
"""
for _ in range(len(l), index + 1):
l.append(fill_value)
l[index] = value
def add_title(g: Graph, subject: URIRef, title: str):
"""Add triples to define the `subject`'s title and label"""
g.add((subject, RDFS.label, Literal(title)))
g.add((subject, NS["titre"], Literal(title)))
def add_index(g: Graph, subject: URIRef, index: int):
"""Add triples to define the `subject`'s index"""
g.add((subject, NS["index"], Literal(index)))
## Generate Protégé display name if a title is set
title = g.value(subject, NS["titre"])
if isinstance(title, Literal):
name = str(subject).split("/")[-1] # Last path component of subject URI
g.add(
(
subject,
NS["__protege_display_name"],
Literal(f"{index:02} | {name} | ") + title,
)
)
# Exceptions ###################################################################
class ParseError(Exception):
pass