Пример #1
0
 def __get_closed_ns(source, publicID):
     g = Graph()
     g.load(source, publicID=publicID)
     names = set()
     for s, _, _ in g:
         try:
             name = g.qname(s)
             if name.startswith('ns1:'):
                 names.add(name[4:])
         except Exception as e:
             if not str(e).startswith("Can't split"):
                 raise e
     return ClosedNamespace(publicID, names)
Пример #2
0
    def __init__(self):
        self.__closed_namespace = ClosedNamespace(
            uri=URIRef('https://onepiece.fandom.com/wiki/'),
            terms=["Blue_Sea",
                   "Ship",
                   "List_of_Canon_Characters",
                   "Category:Organizations",
                   "Devil_Fruit",
                   "List_of_Locations"
                   ]
        )
        self.__root_namespace = Namespace("opw/")
        self.__graph = self.__initialize_graph()
        self.__a_graph = None

        self.__subject_properties = {
            "rname": URIRef("opw/romaji_name"),
            "ename": URIRef("opw/english_name"),
            "first": URIRef("opw/first_episode"),
            "status": URIRef("opw/status"),
            "affiliation": URIRef("opw/affiliation"),
            "captain": URIRef("opw/captain"),
            "occupation": URIRef("opw/occupation"),
            "jname": URIRef("opw/japanese_name"),
            "residence": URIRef("opw/residence"),
            "age": URIRef("opw/age"),
            "birth": URIRef("opw/birthday"),
            "height": URIRef("opw/height"),
            "blood type": URIRef("opw/blood_type"),
            "bounty": URIRef("opw/bounty"),
            "dfname": URIRef("opw/devil_fruit"),
            "name": URIRef("opw/name"),
            "extra1": URIRef("opw/meaning_fruit_type"),
            "meaning": URIRef("opw/meaning"),
            "type": URIRef("opw/type"),
            "real name": URIRef("opw/real_name"),
            "ship": URIRef("opw/ship"),
            "population": URIRef("opw/population"),
            "region": URIRef("opw/region")
        }
Пример #3
0
    'dc',
    'dcterms',
    'oboInOwl',
    'owl',
    'prov',
    'rdf',
    'rdfs',
    'skos',
]

###

dc = ClosedNamespace(uri=URIRef('http://purl.org/dc/elements/1.1/'),
                     terms=[
                         'contributor', 'coverage', 'creator', 'date',
                         'description', 'format', 'identifier', 'language',
                         'publisher', 'relation', 'rights', 'source',
                         'subject', 'title', 'type'
                     ])

dcterms = ClosedNamespace(
    uri=URIRef('http://purl.org/dc/terms/'),
    terms=[
        'Agent', 'AgentClass', 'BibliographicResource', 'Box', 'DCMIType',
        'DDC', 'FileFormat', 'Frequency', 'IMT', 'ISO3166', 'ISO639-2',
        'ISO639-3', 'Jurisdiction', 'LCC', 'LCSH', 'LicenseDocument',
        'LinguisticSystem', 'Location', 'LocationPeriodOrJurisdiction', 'MESH',
        'MediaType', 'MediaTypeOrExtent', 'MethodOfAccrual',
        'MethodOfInstruction', 'NLM', 'Period', 'PeriodOfTime',
        'PhysicalMedium', 'PhysicalResource', 'Point', 'Policy',
        'ProvenanceStatement', 'RFC1766', 'RFC3066', 'RFC4646', 'RFC5646',
Пример #4
0
def personography_to_rdf():
    g = rdflib.Graph()

    skos_terms = [
        "Collection", "Concept", "ConceptScheme", "OrderedCollection", "altLabel", "broadMatch",
        "broader", "changeNote", "closeMatch", "definition", "editorialNote", "exactMatch",
        "example", "hasTopConcept", "hiddenLabel", "historyNote", "inScheme", "mappingRelation",
        "member", "memberList", "narrowMatch", "narrower", "narrowerTransitive", "notation", "note",
        "prefLabel", "related", "relatedMatch", "scopeNote", "semanticRelation", "topConceptOf"
    ]

    skos = ClosedNamespace(
        uri=URIRef("http://www.w3.org/2004/02/skos/core#"),
        terms=skos_terms
    )
    wwo = Namespace("http://www.wwp.brown.edu/ns/1.0#")

    g.bind('skos', skos)
    g.bind('wwo', wwo)

    wwo_person = wwo.Person
    wwo_hasRoleName = wwo.hasRoleName
    wwo_date_of_birth = wwo.dateOfBirth
    wwo_date_of_death = wwo.dateOfDeath
    wwo_place_of_birth = wwo.placeOfBirth
    wwo_place_of_death = wwo.placeOfDeath
    wwo_faith = wwo.faith

    properties = [
        wwo_hasRoleName,
        wwo_date_of_birth,
        wwo_date_of_death,
        wwo_place_of_birth,
        wwo_place_of_death,
        wwo_faith,
    ]

    for prop in chain(properties):
        g.add((prop, RDF.type, RDF.Property))

    g.add((wwo_person, skos.broader, skos.Concept))

    for person in load_personography():
        s = URIRef(f"http://www.wwp.brown.edu/ns/1.0#{person.uid}")

        g.add((s, RDF.type, wwo_person))

        if person.label:
            g.add((s, skos.prefLabel, Literal(person.label)))

        if person.description:
            g.add((s, RDFS.comment, Literal(person.description)))

        for role in person.roles:
            g.add((s, wwo_hasRoleName, Literal(role)))

        for alt_label in person.alternative_labels:
            g.add((s, skos.altLabel, Literal(alt_label)))

        if person.date_of_birth:
            g.add((s, wwo_date_of_birth, Literal(person.date_of_birth)))

        if person.date_of_death:
            g.add((s, wwo_date_of_death, Literal(person.date_of_death)))

        if person.place_of_birth:
            g.add((s, wwo_place_of_birth, Literal(person.place_of_birth)))

        if person.place_of_death:
            g.add((s, wwo_place_of_death, Literal(person.place_of_death)))

        if person.faith:
            g.add((s, wwo_faith, Literal(person.faith)))

    with open(PATH_WWO_PERSONOGRAPHY_RDF, "wb") as f:
        f.write(g.serialize(format='turtle'))
Пример #5
0
WD = Namespace("http://www.wikidata.org/entity/")
WDT = Namespace("http://www.wikidata.org/prop/direct/")

# --- Custom Namespaces
SMGP = Namespace("https://collection.sciencemuseumgroup.org.uk/people/")
SMGO = Namespace("https://collection.sciencemuseumgroup.org.uk/objects/")
SMGD = Namespace("https://collection.sciencemuseumgroup.org.uk/documents/")
HC = ClosedNamespace(
    uri=URIRef("http://www.heritageconnector.org/RDF/"),
    terms=[
        "entityPERSON",
        "entityORG",
        "entityNORP",
        "entityFAC",
        "entityLOC",
        "entityOBJECT",
        "entityLANGUAGE",
        "entityDATE",
        "entityEVENT",
        "database",
    ],
)

# --- Tuple of internal namespaces
_internal = SMGP, SMGO, SMGD


def is_internal_uri(val: Union[str, URIRef, Literal]) -> bool:
    """
    Returns whether a given value (string/rdflib.URIRef/rdflib.Literal) is an internal URI according to heritageconnector.namespace._internal.
Пример #6
0
    "Doru_Doru_no_Mi"
]

name = URIRef("/rname")
meaning = URIRef("/meaning")
first = URIRef("/first")

properties = {
    "name": name,
    "first": first,
    "meaning": meaning,
}

OPW = ClosedNamespace(uri=URIRef('https://onepiece.fandom.com/wiki/'),
                      terms=[
                          "Devil_Fruit", "name", "meaning", "first", "type",
                          "type_url", "user", "url"
                      ])
'''
        "name": name,
        "meaning": meaning_value,
        "first": first_value,
        "type": type_value,
        "type_url": type_url,
        "user": user_value,
        "url": url
'''


def get_devilFruitG(graph):
    for dfruit in DEVIL_FRUITS:
Пример #7
0
DSO = ClosedNamespace(
    uri=URIRef('http://www.semanticweb.org/directory-service-ontology#'),
    terms=[
        # Classes
        'Register',
        'RegisterResult',
        'RegisterAction',
        'Deregister',
        'InfoAgent',
        'ServiceAgent',
        'Search',
        'SolverAgent',
        'Modify',

        # Object properties
        'AgentType',

        # Data properties
        'Uri',
        'Name',
        'Address',

        # Named Individuals
        'FlightsAgent',
        'HotelsAgent',
        'TravelServiceAgent',
        'PersonalAgent',
        'WeatherAgent',
        'PaymentAgent',
        'AgenteInteracciones',
        'AgenteGestorDeCancelaciones',
        'AgenteGestorDePagos',
        'AgenteInteracciones',
        'AgenteObtenedorDeOfertasDeActividades',
        'AgenteObtenedorDeOfertasDeAlojamiento',
        'AgenteObtenedorDeOfertasDeDesplazamiento',
        'AgenteProcesador',
        'SimplyDirectoryService',
        'AgenciasDeTransporte',
        'AgenteUsuario',
        'CentrosDeActividades',
        'HotelesYotrosAlojamientos',
        'ServicioDeClima'
    ])
Пример #8
0
 def setUp(self):
     self.ns_str = "http://example.com/name/space/"
     self.ns = ClosedNamespace(self.ns_str, ["a", "b", "c"])
Пример #9
0
OSLC_RM = ClosedNamespace(
    uri=URIRef("http://open-services.net/ns/rm#"),
    terms=[
        # RDFS Classes in this namespace
        "Requirement",
        "RequirementCollection",

        # RDF Properties in this namespace
        # for Requirement
        "affectedBy",
        "elaboratedBy",
        "implementedBy",
        "specifiedBy",
        "satisfiedBy",
        "trackedBy",
        "validatedBy",

        # for RequirementCollection
        "uses",
        # General
        "elaborates",
        "specifies",
        "satisfies",
        "decomposedBy",
        "decomposes",
        "constrainedBy",
        "constrains",
        "rmServiceProviders",
    ])
Пример #10
0
if __name__ == '__main__':

    DATA_FOLDER = (sys.argv[1] if len(sys.argv) == 2 else str(Path.home()) +
                   '/data/phenodb')
    print(DATA_FOLDER)

    PHENO = ClosedNamespace(
        uri=URIRef("http://phenodb.phenomebrowser.net/"),
        terms=[
            #Classes
            "Disease",
            "Drug",
            "Device",
            "Gene",
            "Genotype",
            "Phenotype",
            "Pathogen",
            "Provenance",
            "Association",

            #Properties
            "ecNumber",
            "uniprotId",
            "url",
            "failedToContributeToCondition"
        ])

    OBO = ClosedNamespace(
        uri=URIRef("http://purl.obolibrary.org/obo/"),
        terms=[
            #has evidence
            "RO_0002558",
Пример #11
0
from rdflib import URIRef
from rdflib.namespace import ClosedNamespace

JFS = ClosedNamespace(
    uri=URIRef("http://jazz.net/xmlns/prod/jazz/jfs/1.0/"),
    terms=[
        # RDFS Classes in this namespace

        # RDF Properties in this namespace
        # for OAuth
        "oauthRealmName",
        "oauthDomain",
        "oauthRequestConsumerKeyUrl",
        "oauthApprovalModuleUrl",
        "oauthRequestTokenUrl",
        "oauthUserAuthorizationUrl",
        "oauthAccessTokenUrl",
        "nonLocalizedTitle",
        "version",
        "instanceName",
    ])
Пример #12
0
OSLC = ClosedNamespace(
    uri=URIRef("http://open-services.net/ns/core#"),
    terms=[
        # RDFS Classes in this namespace
        "AllowedValues",
        "AttachmentContainer",
        "AttachmentDescriptor",
        "Comment",
        "Compact",
        "CreationFactory",
        "Dialog",
        "Discussion",
        "Error",
        "ExtendedError",
        "OAuthConfiguration",
        "PrefixDefinition",
        "Preview",
        "Property",
        "Publisher",
        "QueryCapability",
        "ResourceShape",
        "ResponseInfo",
        "Service",
        "ServiceProvider",
        "ServiceProviderCatalog",
        "Compact",
        "Preview",

        # RDF Properties in this namespace
        "allowedValue",
        "allowedValues",
        "archived",
        "attachment",
        "attachmentSize",
        "authorizationURI",
        "comment",
        "creation",
        "creationDialog",
        "creationFactory",
        "default",
        "defaultValue",
        "describes",
        "details",
        "dialog",
        "discussedBy",
        "discussionAbout",
        "document",
        "domain",
        "error",
        "executes",
        "extendedError",
        "futureAction",
        "hidden",
        "hintHeight",
        "hintWidth",
        "icon",
        "iconAltLabel",
        "iconSrcSet",
        "iconTitle",
        "impactType",
        "initialHeight",
        "inReplyTo",
        "instanceShape",
        "inverseLabel",
        "isMemberProperty",
        "label",
        "largePreview",
        "maxSize",
        "message",
        "modifiedBy",
        "moreInfo",
        "name",
        "nextPage",
        "oauthAccessTokenURI",
        "oauthConfiguration",
        "oauthRequestTokenURI",
        "occurs",
        "partOfDiscussion",
        "postBody",
        "prefix",
        "prefixBase",
        "prefixDefinition",
        "property",
        "propertyDefinition",
        "queryable",
        "queryBase",
        "queryCapability",
        "range",
        "readOnly",
        "rel",
        "representation",
        "resourceShape",
        "resourceType",
        "results",
        "selectionDialog",
        "service",
        "serviceProvider",
        "serviceProviderCatalog",
        "shortId",
        "shortTitle",
        "smallPreview",
        "statusCode",
        "totalCount",
        "usage",
        "valueShape",
        "valueType",
        "publisher",
        "document",
        "hintHeight",
        "hintWidth",
        "initialHeight",
        "icon",
        "smallPreview",
        "largePreview",
    ])
Пример #13
0
def load_skill_nodes_from_rdf_resources(skills_resource_dir) -> Set[OntNode]:
    """
    Load skills in rdf format from resource directory and return as list node
    """

    global skill_nodes_cache
    if skill_nodes_cache is not None:
        return skill_nodes_cache

    ont_files = []
    try:
        for f in listdir(skills_resource_dir):
            f_path = join(skills_resource_dir, f)
            if isfile(f_path) and f_path.endswith(".ttl"):
                ont_files.append(f_path)
    except FileNotFoundError:
        app.logger.info("Please copy *.ttl file to directory {}".format(
            skills_resource_dir))
        raise

    if len(ont_files) == 0:
        app.logger.debug("Ontology (.ttl) files is not found")
        return set()

    app.logger.debug('Load ontology files: {}'.format(ont_files))

    skills = set()
    for ont_file in ont_files:
        try:
            graph = rdflib.Graph()
            graph.parse(ont_file, format="ttl")

            base_namespace_uri = get_namespace_uri(g=graph,
                                                   namespace_prefix=None)

            triples = graph.triples((None, RDF.type, None))
            for s, p, o in triples:
                if not (o == OWL.NamedIndividual) and not (o == OWL.Class):
                    continue

                subject = split_triple(s)
                object = split_triple(o)
                ontNode = OntNode(subject[0], subject[1], type=object[1])
                skills.add(ontNode)

                # Labels if exists
                triples_labels = graph.triples((s, RDFS.label, None))
                labels = [split_triple(o2)[1] for s2, p2, o2 in triples_labels]
                ontNode.labels = labels

                # Parents
                if o == OWL.NamedIndividual:
                    triples_parents = graph.triples((s, RDF.type, None))
                    parents = [
                        split_triple(o2)[1] for s2, p2, o2 in triples_parents
                        if o2 != OWL.NamedIndividual
                    ]
                    ontNode.parents = parents
                else:
                    o_parents = graph.transitive_objects(
                        subject=s, property=RDFS.subClassOf)
                    parents = [
                        split_triple(o2)[1] for o2 in o_parents
                        if split_triple(o2)[1] != ontNode.name
                    ]
                    ontNode.parents = parents

                # Custom properties
                RDF_SKILL_PROPERTY = ClosedNamespace(
                    uri=URIRef(str(base_namespace_uri)),
                    terms=["difficulty", "keywordOnly"])

                triples_difficulty = graph.triples(
                    (s, RDF_SKILL_PROPERTY.difficulty, None))
                for s2, p2, o2 in triples_difficulty:
                    try:
                        ontNode.difficulty = int(o2)
                    except ValueError:
                        app.logger.debug(
                            "difficulty {} of {} not an int!".format(
                                o2, ontNode.name))

                triples_keyword_only = graph.triples(
                    (s, RDF_SKILL_PROPERTY.keywordOnly, None))
                for s2, p2, o2 in triples_keyword_only:
                    try:
                        ontNode.keyword_only = bool(o2)
                    except ValueError:
                        app.logger.debug(
                            "o_keyword_only {} of {} not an bool!".format(
                                o2, ontNode.name))
        except BaseException:
            app.logger.debug("Parse file {} exception".format(ont_file))
            raise

    skill_nodes_cache = skills
    return skills
Пример #14
0
# In[11]:

ldc_entity_types_new = []
for t in ldc_entity_types:
    sp = t.split('.')
    if sp[0] not in long_to_short_map:
        print(t)
    else:
        sp[0] = long_to_short_map[sp[0]]
    ldc_entity_types_new.append('.'.join(sp))

# In[12]:

LDC_ONTOLOGY = ClosedNamespace(uri=URIRef(
    "https://tac.nist.gov/tracks/SM-KBP/2019/ontologies/LDCOntology#"),
                               terms=ldc_entity_types_new + ldc_event_types)

# In[13]:

with open('../../results/det_results_merged_34a.pkl', 'rb') as fin:
    det_results_jpg = pickle.load(fin)

with open('../../results/det_results_merged_34b.pkl', 'rb') as fin:
    det_results_vid = pickle.load(fin)

# In[14]:

with open('../temp/imgsize_m18_jpg.pkl', 'rb') as fin:
    image_shape = pickle.load(fin)
with open('../temp/imgsize_m18_kf.pkl', 'rb') as fin:
Пример #15
0
from rdflib import URIRef
from rdflib.namespace import ClosedNamespace

OSLC_TRS = ClosedNamespace(
    uri=URIRef("http://open-services.net/ns/core/trs#"),
    terms=[
        # RDFS Classes in this namespace
        "ResourceSet",
        "Resource",
        "TrackedResourceSet",
        "ChangeLog",
        "Creation",
        "Modification",
        "Deletion",

        # RDF Properties in this namespace
        "trackedResourceSet",
        "base",
        "changeLog",
        "cutoffEvent",
        "change",
        "previous",
        "changed",
        "order",
    ])
Пример #16
0
from rdflib import URIRef
from rdflib.namespace import ClosedNamespace

OSLC_CONFIG = ClosedNamespace(
    uri=URIRef("http://open-services.net/ns/config#"),
    terms=[
        # RDFS Classes in this namespace
        "Configuration",
        "Stream",

        # RDF Properties in this namespace
        "cmServiceProviders",
    ])

PROV = ClosedNamespace(
    uri=URIRef("http://www.w3.org/ns/prov#"),
    terms=["wasDerivedFrom", "wasRevisionOf", "wasGeneratedBy"])
Пример #17
0
""" % KTBS_NS_URI

KTBS_NS_GRAPH = Graph("IOMemory", identifier=KTBS_NS_URIREF)
KTBS_NS_GRAPH.load(StringIO(KTBS_NS_TTL), KTBS_NS_URIREF, "n3")

KTBS_IDENTIFIERS = set()

for subject, _, _ in KTBS_NS_GRAPH.triples((None, RDF.type, None)):
    if subject.startswith(KTBS_NS_URI):
        splitted = subject.split("#", 1)
        if len(splitted) > 1:
            KTBS_IDENTIFIERS.add(splitted[1])

KTBS = ClosedNamespace(
    KTBS_NS_URI + "#",
    KTBS_IDENTIFIERS,
)


class _KtbsNsResource(LocalCore):
    """I am the only resource class of KTBS_NS_SERVICE.

    KTBS_NS_SERVICE provides a local copy of the kTBS namespace.
    """
    # too few public methods (1/2) #pylint: disable=R0903
    RDF_MAIN_TYPE = URIRef("http://www.w3.org/2002/07/owl#Ontology")

    @classmethod
    def init_service(cls, service):
        """I populate a service the kTBS namespace at its root.
        """
Пример #18
0
from rdflib import URIRef
from rdflib.namespace import ClosedNamespace

PYOSLC = ClosedNamespace(uri=URIRef("http://example.com/ns/pyoslc#"),
                         terms=[
                             "TrackedResourceSetProvider",
                         ])
Пример #19
0
from rdflib.namespace import ClosedNamespace
from rdflib import URIRef

Dcterms = ClosedNamespace(uri=URIRef("http://purl.org/dc/terms/"),
                          terms=["title"])

SBOL2 = ClosedNamespace(
    uri=URIRef("http://sbols.org/v2#"),
    terms=[
        # types
        "ComponentDefinition",
        "Component",
        "ModuleDefinition",
        "Module",
        "Interaction",
        "Participation",
        "MapsTo",
        "Sequence",
        "SequenceConstraint",
        "FunctionalComponent",

        # predicates
        "component",
        "displayId",
        "type",
        "role",
        "persistentIdentity",
        "version",
        "interaction",
        "participant",
        "mapsTo",
Пример #20
0
ACL = ClosedNamespace(
    uri=URIRef('http://www.nuin.org/ontology/fipa/acl'),
    terms=[
        # Classes
        'FipaAclMessage',
        'KsMessage',
        'SpeechAct',

        # Object properties
        'receiver',
        'reply-to',
        'ontology',
        'performative',
        'sender',

        # Data properties
        'language',
        'encoding',
        'content',
        'reply-by',
        'reply-with',
        'conversation-id',
        'in-reply-to',

        # Named Individuals
        'refuse',
        'subscribe',
        'agree',
        'query-ref',
        'request',
        'request-whenever',
        'query-if',
        'proxy',
        'cancel',
        'propose',
        'cfp',
        'reject-proposal',
        'failure',
        'accept-proposal',
        'not-understood',
        'inform',
        'inform-if',
        'inform-ref',
        'propagate',
        'confirm',
        'request-when',
        'disconfirm'
    ])
Пример #21
0
AIDA_PROGRAM_ONTOLOGY = ClosedNamespace(
    uri=URIRef("http://www.isi.edu/aida/programOntology#"),
    terms=[
        "Person",
        "Organization",
        "Location",
        "Facility",
        "GeopoliticalEntity",
        "String",
        # realis types
        "Actual",
        "Generic",
        "Other",
        # relation types
        "conflict.attack",
        "conflict.demonstrate",
        "contact.broadcast",
        "contact.contact",
        "contact.correspondence",
        "contact.meet",
        "justice.arrest-jail",
        "life.die",
        "life.injure",
        "manufacture.artifact",
        "movement.transport-artifact",
        "movement.transport-person",
        "personnel.elect",
        "personnel.end-position",
        "personnel.start-position",
        "transaction.transaction",
        "transaction.transfer-money",
        "transaction.transfer-ownership",
        "children",
        "parents",
        "other_family",
        "parents",
        "children",
        "siblings",
        "spouse",
        "employee_or_member_of",
        "employees_or_members",
        "schools_attended",
        "students",
        "city_of_birth",
        "births_in_city",
        "stateorprovince_of_birth",
        "births_in_stateorprovince",
        "country_of_birth",
        "births_in_country",
        "cities_of_residence",
        "residents_of_city",
        "statesorprovinces_of_residence",
        "residents_of_stateorprovince",
        "countries_of_residence",
        "residents_of_country",
        "city_of_death",
        "deaths_in_city",
        "stateorprovince_of_death",
        "deaths_in_stateorprovince",
        "country_of_death",
        "deaths_in_country",
        "shareholders",
        "holds_shares_in",
        "founded_by",
        "organizations_founded",
        "top_members_employees",
        "top_member_employee_of",
        "members",
        "member_of",
        "subsidiaries",
        "city_of_headquarters",
        "headquarters_in_city",
        "stateorprovince_of_headquarters",
        "headquarters_in_stateorprovince",
        "country_of_headquarters",
        "headquarters_in_country",
        "alternate_names",
        "alternate_names",
        "date_of_birth",
        "political_religious_affiliation",
        "age",
        "number_of_employees_members",
        "origin",
        "date_founded",
        "date_of_death",
        "date_dissolved",
        "cause_of_death",
        "website",
        "title",
        "religion",
        "charges"
    ])
Пример #22
0
def depositions_to_rdf(persons: List[Person], places: List[Place], entity_to_documents: Dict[str, str]):
    g = rdflib.Graph()

    skos_terms = [
        "Collection", "Concept", "ConceptScheme", "OrderedCollection", "altLabel", "broadMatch",
        "broader", "changeNote", "closeMatch", "definition", "editorialNote", "exactMatch",
        "example", "hasTopConcept", "hiddenLabel", "historyNote", "inScheme", "mappingRelation",
        "member", "memberList", "narrowMatch", "narrower", "narrowerTransitive", "notation", "note",
        "prefLabel", "related", "relatedMatch", "scopeNote", "semanticRelation", "topConceptOf"
    ]

    skos = ClosedNamespace(
        uri=URIRef("http://www.w3.org/2004/02/skos/core#"),
        terms=skos_terms
    )
    depositions = Namespace("http://www.gleipnir.de/1641/ns/1.0#")

    g.bind('skos', skos)
    g.bind('depo', depositions)

    depo_person = depositions.Person
    depo_has_title = depositions.hasTitle
    depo_place_of_birth = depositions.placeOfBirth
    depo_mentioned_in = depositions.mentionedIn

    depo_place = depositions.Place
    depo_county = depositions.County
    depo_in_county = depositions.county

    depo_dbpedia = depositions.dbpedia

    properties = [
        depo_person,
        depo_place,
        depo_has_title,
        depo_place_of_birth,
        depo_dbpedia,
        depo_mentioned_in,
        depo_county,
        depo_in_county
    ]

    for prop in properties:
        g.add((prop, RDF.type, RDF.Property))

    g.add((depo_person, skos.broader, skos.Concept))
    g.add((depo_place, skos.broader, skos.Concept))
    g.add((depo_county, skos.broader, skos.Concept))

    for person in persons:
        s = URIRef(person.new_iri)

        g.add((s, RDF.type, depo_person))

        if person.label:
            g.add((s, skos.prefLabel, Literal(person.label)))

        if person.description:
            g.add((s, RDFS.comment, Literal(person.description)))

        if person.title:
            g.add((s, depo_has_title, Literal(person.title)))

        if person.alt_label:
            g.add((s, skos.altLabel, Literal(person.alt_label)))

        if person.birth_place:
            g.add((s, depo_place_of_birth, Literal(person.birth_place)))

        if person.old_iri.startswith("http://dbpedia.org/"):
            g.add((s, depo_dbpedia, URIRef(person.old_iri)))

        for doc in entity_to_documents[person.old_iri]:
            g.add((s, depo_mentioned_in, URIRef("http:" + doc)))

    counties = [
        "Antrim",
        "Armagh",
        "Carlow",
        "Cavan",
        "Clare",
        "Cork",
        "Derry",
        "Donegal",
        "Down",
        "Dublin",
        "Fermanagh",
        "Galway",
        "Kerry",
        "Kildare",
        "Kilkenny",
        "Laois",
        "Leitrim",
        "Limerick",
        "Longford",
        "Louth",
        "Mayo",
        "Meath",
        "Monaghan",
        "Offaly",
        "Roscommon",
        "Sligo",
        "Tipperary",
        "Tyrone",
        "Waterford",
        "Westmeath",
        "Wexford",
        "Wicklow",
    ]

    # Convert counties
    for county in counties:
        county_iri = f"http://www.gleipnir.de/1641/ns/1.0#County_{county}"
        s = URIRef(county_iri)

        g.add((s, RDF.type, depo_county))

        dbpedia_iri = f"http://dbpedia.org/resource/County_{county}"

        g.add((s, depo_dbpedia, URIRef(dbpedia_iri)))
        label, description = get_dpbedia_label_description(dbpedia_iri)

        if label:
            g.add((s, skos.prefLabel, Literal(label)))

        if description:
            g.add((s, RDFS.comment, Literal(description)))

    # Convert places
    for place in places:
        s = URIRef(place.new_iri)

        g.add((s, RDF.type, depo_place))

        if place.label:
            g.add((s, skos.prefLabel, Literal(place.label)))

        if place.description:
            g.add((s, RDFS.comment, Literal(place.description)))

        if place.alt_label:
            g.add((s, skos.altLabel, Literal(place.alt_label)))

        if place.old_iri.startswith("http://dbpedia.org/"):
            g.add((s, depo_dbpedia, URIRef(place.old_iri)))

        if "County" in place.description and not place.old_iri.startswith("http://dbpedia.org/"):
            name = place.description.split()[-1]
            county_iri = build_new_iri(f"County_{name}")
            g.add((s, depo_in_county, URIRef(county_iri)))

        for doc in entity_to_documents[place.old_iri]:
            g.add((s, depo_mentioned_in, URIRef("http:" + doc)))

    os.makedirs(os.path.dirname(PATH_DEPOSITIONS_KB), exist_ok=True)

    with open(PATH_DEPOSITIONS_KB, "wb") as f:
        f.write(g.serialize(format='turtle', encoding="utf-8"))
Пример #23
0
 Translated to RDFlib from ontology http://www.nuin.org/ontology/fipa/acl

 :Date 16/12/2020 18:22:11
"""
from rdflib import URIRef
from rdflib.namespace import ClosedNamespace

ACL =  ClosedNamespace(
    uri=URIRef('http://www.nuin.org/ontology/fipa/acl'),
    terms=[
        # Classes
        'SpeechAct',
        'FipaAclMessage',
        'KsMessage',
        # Object properties
        'sender',
        'receiver',
        'ontology',
        'reply_to',
        'performative',
        # Data properties
        'reply_by',
        'conversation_id',
        'encoding',
        'in_reply_to',
        'reply_with',
        'content',
        'language'
    ]
)
Пример #24
0
DSO = ClosedNamespace(
    uri=URIRef('http://www.semanticweb.org/directory-service-ontology#'),
    terms=[
        # Classes
        'Register',
        'RegisterResult',
        'RegisterAction',
        'Deregister',
        'InfoAgent',
        'ServiceAgent',
        'Search',
        'SolverAgent',
        'Modify',

        # Object properties
        'AgentType',

        # Data properties
        'Uri',
        'Name',
        'Address',

        # Named Individuals
        'FlightsAgent',
        'HotelsAgent',
        'TravelServiceAgent',
        'PersonalAgent',
        'WeatherAgent',
        'PaymentAgent'
    ])
Пример #25
0
    'isMemberOfCollection',
    'hasCollectionMember',
    'isDerivationOf',
    'hasDerivation',
    'isDependentOf',
    'hasDependent',
    'isDescriptionOf',
    'HasDescription',
    'isMetadataFor',
    'HasMetadata',
    'isAnnotationOf',
    'HasAnnotation',
    'hasEquivalent',
]

relsext = ClosedNamespace('info:fedora/fedora-system:def/relations-external#',
                          fedora_rels)
''':class:`rdflib.namespace.ClosedNamespace` for the `Fedora external
relations ontology
<http://www.fedora.info/definitions/1/0/fedora-relsext-ontology.rdfs>`_.
'''

# TODO: find and catalog full namespace. currently this is just a list of
# names we use in this ns.
model = ClosedNamespace('info:fedora/fedora-system:def/model#', [
    'hasModel',
])
''':class:`rdflib.namespace.ClosedNamespace` for the Fedora model
namespace (currently only includes ``hasModel``).'''

# these are the OAI terms used with the PROAI OAI provider commonly used with Fedora
# (terms not actually defined at the namespace specified...)
Пример #26
0
from rdflib import URIRef
from rdflib.namespace import ClosedNamespace

OAUTH = ClosedNamespace(
    uri=URIRef("http://example.com/pyoslc/server/oauth#"),
    terms=[
        # RDFS Classes in this namespace
        "Consumer",

        # RDF Properties in this namespace
        "consumerName",
        "consumerKey",
        "consumerSecret",
        "provisional",
        "trusted",
        "callback"
    ])
Пример #27
0
from rdflib import URIRef
from rdflib.namespace import ClosedNamespace

OSLCData = ClosedNamespace(
    uri=URIRef("http://open-services.net/ns/servicemanagement/1.0/"),
    terms=[
        # RDFS Classes in this namespace
        # RDF Properties in this namespace
    ])
Пример #28
0
from rdflib import URIRef, Graph
from rdflib.namespace import ClosedNamespace, RDF

OPW = ClosedNamespace(uri=URIRef('https://onepiece.fandom.com/wiki/'),
                      terms=["List_of_Canon_Characters"])

g = Graph()

monkey_d_luffy = URIRef("https://onepiece.fandom.com/wiki/Monkey_D._Luffy")

g.add((monkey_d_luffy, RDF.type, OPW.List_of_Canon_Characters))


def update_graph_for_fruits(g):
    gomi_gomi = URIRef("")

    # TODO more properties

    g.add()

    return g


print(g.serialize(format="xml").decode("utf-8"))
Пример #29
0
# Seedling Ontology. Currently Hardcoded
SEEDLING_TYPES_NIST = ClosedNamespace(
    uri=URIRef("https://tac.nist.gov/tracks/SM-KBP/2018/ontologies/SeedlingOntology#"),
    terms=["Person", "Organization", "Location", "Facility", "GeopoliticalEntity", "FillerType",
           "Business.DeclareBankruptcy", "Business.End", "Business.Merge", "Business.Start",
           "Conflict.Attack", "Conflict.Demonstrate",
           "Contact.Broadcast", "Contact.Contact", "Contact.Correspondence", "Contact.Meet",
           "Existence.DamageDestroy",
           "Government.Agreements", "Government.Legislate", "Government.Spy", "Government.Vote",
           "Inspection.Artifact", "Inspection.People",
           "Justice.Acquit", "Justice.Appeal", "Justice.ArrestJail", "Justice.ChargeIndict", "Justice.Convict",
           "Justice.Execute", "Justice.Extradite", "Justice.Fine", "Justice.Investigate", "Justice.Pardon",
           "Justice.ReleaseParole", "Justice.Sentence", "Justice.Sue", "Justice.TrialHearing",
           "Life.BeBorn", "Life.Die", "Life.Divorce", "Life.Injure", "Life.Marry",
           "Manufacture.Artifact",
           "Movement.TransportArtifact", "Movement.TransportPerson",
           "Personnel.Elect", "Personnel.Elect_Elect", "Personnel.Elect_Place", "Personnel.EndPosition", "Personnel.Nominate", "Personnel.StartPosition",
           "Transaction.Transaction", "Transaction.TransferControl", "Transaction.TransferMoney",
           "Transaction.TransferOwnership",
           "GeneralAffiliation.APORA", "GeneralAffiliation.APORA_Affiliate", "GeneralAffiliation.APORA_Affiliation", "GeneralAffiliation.MORE", "GeneralAffiliation.OPRA",
           "GeneralAffiliation.OrganizationWebsite", "GeneralAffiliation.PersonAge", "GeneralAffiliation.Sponsorship",
           "Measurement.Count",
           "OrganizationAffiliation.EmploymentMembership", "OrganizationAffiliation.Founder",
           "OrganizationAffiliation.InvestorShareholder", "OrganizationAffiliation.Leadership",
           "OrganizationAffiliation.Ownership", "OrganizationAffiliation.StudentAlum",
           "PartWhole.Membership", "PartWhole.Subsidiary",
           "PersonalSocial.Business", "PersonalSocial.Family", "PersonalSocial.RoleTitle",
           "PersonalSocial.Unspecified",
           "Physical.LocatedNear", "Physical.OrganizationHeadquarter", "Physical.OrganizationLocationOrigin",
           "Physical.Resident", "Weapon", "Vehicle"])
AIDA_PROGRAM_ONTOLOGY = ClosedNamespace(
    uri=URIRef("http://www.isi.edu/aida/programOntology#"),
    terms=[
        "Person",
        "Organization",
        "Location",
        "Facility",
        "GeopoliticalEntity",
        "String",
        # realis types
        "Actual",
        "Generic",
        "Other",
        # relation types
        "conflict.attack",
        "conflict.demonstrate",
        "contact.broadcast",
        "contact.contact",
        "contact.correspondence",
        "contact.meet",
        "justice.arrest-jail",
        "life.die",
        "life.injure",
        "manufacture.artifact",
        "movement.transport-artifact",
        "movement.transport-person",
        "personnel.elect",
        "personnel.end-position",
        "personnel.start-position",
        "transaction.transaction",
        "transaction.transfer-money",
        "transaction.transfer-ownership",
        "children",
        "parents",
        "other_family",
        "parents",
        "children",
        "siblings",
        "spouse",
        "employee_or_member_of",
        "employees_or_members",
        "schools_attended",
        "students",
        "city_of_birth",
        "births_in_city",
        "stateorprovince_of_birth",
        "births_in_stateorprovince",
        "country_of_birth",
        "births_in_country",
        "cities_of_residence",
        "residents_of_city",
        "statesorprovinces_of_residence",
        "residents_of_stateorprovince",
        "countries_of_residence",
        "residents_of_country",
        "city_of_death",
        "deaths_in_city",
        "stateorprovince_of_death",
        "deaths_in_stateorprovince",
        "country_of_death",
        "deaths_in_country",
        "shareholders",
        "holds_shares_in",
        "founded_by",
        "organizations_founded",
        "top_members_employees",
        "top_member_employee_of",
        "members",
        "member_of",
        "subsidiaries",
        "city_of_headquarters",
        "headquarters_in_city",
        "stateorprovince_of_headquarters",
        "headquarters_in_stateorprovince",
        "country_of_headquarters",
        "headquarters_in_country",
        "alternate_names",
        "alternate_names",
        "date_of_birth",
        "political_religious_affiliation",
        "age",
        "number_of_employees_members",
        "origin",
        "date_founded",
        "date_of_death",
        "date_dissolved",
        "cause_of_death",
        "website",
        "title",
        "religion",
        "charges"
    ])