From 2de5293227950624c4b7f4bd0856d43db76d32e2 Mon Sep 17 00:00:00 2001 From: Simon Gray Date: Mon, 19 Dec 2022 11:24:15 +0100 Subject: [PATCH] #3 - import open English WordNet - add relevant schemas - move hash functions to separate ns - also include hash of prefix data --- .gitignore | 5 +- resources/schemas/external/lime.xml | 832 +++++++++++++++++++++ resources/schemas/external/synsem.xml | 513 +++++++++++++ src/main/dk/cst/dannet/bootstrap.clj | 75 +- src/main/dk/cst/dannet/db.clj | 29 +- src/main/dk/cst/dannet/hash.clj | 64 ++ src/main/dk/cst/dannet/prefix.cljc | 126 ++-- src/main/dk/cst/dannet/web/components.cljc | 3 +- 8 files changed, 1521 insertions(+), 126 deletions(-) create mode 100644 resources/schemas/external/lime.xml create mode 100644 resources/schemas/external/synsem.xml create mode 100644 src/main/dk/cst/dannet/hash.clj diff --git a/.gitignore b/.gitignore index 7832dbaa..a894bb1d 100644 --- a/.gitignore +++ b/.gitignore @@ -18,6 +18,9 @@ bootstrap/other/cor/ddo_bet_corextlink.csv # File sent by Sanni in email on 2022-05-23 (renamed). bootstrap/other/sentiment/sense_polarities.tsv +# The open English WordNet +bootstrap/other/english/english-wordnet-2021.ttl + .cpcache .DS_Store @@ -30,4 +33,4 @@ resources/public/js/compiled out/ target/ dannet.jar -db/ +/db/ diff --git a/resources/schemas/external/lime.xml b/resources/schemas/external/lime.xml new file mode 100644 index 00000000..b6c26d7e --- /dev/null +++ b/resources/schemas/external/lime.xml @@ -0,0 +1,832 @@ + + + + + + + + + + + + + + + ]> + + + + + + Lexicon Model for Ontologies - LIngusitic MEtadata (LIME) + 1.1 + 2016-01-10 + 2016-01-10 + http://www.w3.org/ns/lemon/lime# + lime + CC-Zero + LIME (LInguistic MEtadata) is a vocabulary for expressing linguistic metadata about linguistic resources and linguistically grounded datasets. + Vocabulary of Linguistic Metadata + + + + + + + + + + + + + + + + + -Version 1.0: depreciation with minor change in metadata for LOV publication + -Version 1.1: creation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Konzeptdatensatz + conceptual dataset + conjunto de conceptos + banque de concepts + banca concetti + dataset van begrippen + концептуальный набор данных + stable + http://www.w3.org/ns/lemon/lime + stable + The 'conceptual dataset' property relates a lexical link set or a conceptualization set to a corresponding concept set. + Свойство 'концептуальный набор данных' связывает набор лексической связи или концептуализацию с соответствующим набором понятий. + + + + + + + + + + + + + + + + + inskrywing + Eintrag + entry + entrada + entrée + entrata + Item + entrada + înregistrare + ingång + запись + http://www.w3.org/ns/lemon/lime + stable + stable + The 'entry' property relates a lexicon to one of the lexical entries contained in it. + Свойство 'запись' связывает лексикон с одной из содержащихся в нем словарных единиц. + + + + + + + + + + + + + + + + + + + + leksikale datastel + Lexikondatensatz + lexicon dataset + conjunto de datos del lexicón + banque de données lexicales + banca dati lessicale + lexicale dataset + set de date de lexicon + lexikondatamängd + лексический набор данных + The 'lexicon dataset' property indicates the lexicon that contains the entries refered to in a lexicalization set or a conceptualization set. + Свойство 'лексический набор данных' указывает лексику, которая содержит записи, упомянутые в наборе лексикализации или наборе концептуализации. + stable + + stable + + + + + + + + + + + + + + + + + linguistische Kategorienmodell + lingustic catalog + conjunto de categoríes lingüísticas + banque de catégories linguistiques + banca categorie linguistiche + verzameling van taalkundige categories + лингвистический каталог + The 'linguistic catalog' property indicates the catalog of linguistic categories used in a lexicon to define linguistic properties of lexical entries. + Свойство 'лингвистический каталог' указывает каталог языковых категорий, используемых в лексиконе, для определения лингвистических свойств словарных единиц. + http://www.w3.org/ns/lemon/lime + stable + stable + + + + + + + + + + Teilung + partition + partición + partition + partizione + verdeling + раздел + The 'partition' property relates a lexicalization set or lexical linkset to a logical subset that contains lexicalizations for a given ontological type only. + Свойство 'раздел' связывает набор лексикализации или лексический набор ссылок с логическим подмножеством, который содержит лексикализацию только для данного онтологического типа. + + + stable + + + + + + + + + + + + + + + + + + + + + + + + + verwysingsdatastel + Referenzdatensatz + reference dataset + conjunto de datos de referencia + banque de réfèrences + banca riferimenti + verzameling van referenties + setul de date de referință + referensdatamängd + справочный набор данных + The 'reference dataset' property indicates the dataset that contains the domain objects or vocabulary elements that are either referenced by a given lexicon, providing the grounding vocabulary for the meaning of the lexical entries, or linked to lexical concepts in a concept set by means of a lexical link set. + Свойство 'справочный набор данных' указывает набор данных, который содержит объекты домена или элементы словаря, на которые либо ссылается данный лексикон, обеспечивая базовый словарь для значения словарных единиц или связывая лексическими понятия с понятийными наборами, заданными с помощью набора лексических ссылок. + + + stable + + + + + + + + + + + + + + + + + Ressourcentyp + resource type + tipo de recurso + type de ressource + tipo di risorsa + тип ресурса + type van ressource + http://www.w3.org/ns/lemon/lime + stable + The 'resource type' property indicates the type of ontological entity of a lexicalization set or lexical linkset. + Свойство 'тип ресурса' указывает тип онтологического объекта набора лексикализации или лексического набора ссылок. + + + + + + + + + + + + + + + + + + + + + + Durchschnittliche Amiguität + average ambiguity + ambigüedad promedia + ambiguïté moyenne + ambiguità media + gemiddelde ambiguïteit + средняя неоднозначность + The 'average ambiguity' property indicates the average number of lexical concepts evoked by each lemma/canonical form in the lexicon. + Свойство 'средней неоднозначности' указывает среднее число лексических понятий, вызываемых каждой леммой/канонической формой в лексиконе. + http://www.w3.org/ns/lemon/lime + stable + + + + + + + + + + gemiddelde aantal leksikaliserings + Durchschnittliche Anzahl von Lexikalisierungen + average number of lexicalizations + среднее количество лексикализаций + promedio de lexicalizaciones + nombre moyen de lexicalisations + numero medio di lessicalizzazioni + gemiddeld aantal van lexicalisatie + numero medio de lexicalizações + numărul mediu de lexicalizari + genomsnittligt antal lexikaliseringar + http://www.w3.org/ns/lemon/lime + stable + The 'average number of lexicalizations' property indicate the average number of lexicalizations per ontology element. The exact formula for calculating the average is indicated in the specification: https://www.w3.org/community/ontolex/wiki/Final_Model_Specification#LexicalizationSet + Свойство 'среднее количество лексикализаций' указывает среднее число лексикализаций на элемент онтологии. Точная формула для вычисления среднего значения указана в спецификации: https://www.w3.org/community/ontolex/wiki/Final_Model_Specification#LexicalizationSet + + + + + + + + + + Durchschnittliche Anzahl von Links + average number of links + среднее количество ссылок + promedio de enlaces + nombre moyen de liens + numero medio di link + gemiddeld aantal van links + http://www.w3.org/ns/lemon/lime + stable + The 'average number of links' property indicates the average number of links for each entity in the conceptual dataset. + Свойство 'среднее количество ссылок' указывает среднее число ссылок для каждого объекта в концептуальном наборе данных. + + + + + + + + + + Durchschnittliche Synonymie + average synonymy + средняя синонимия + sinóminedad promedia + synonymie moyenne + sinonimità media + gemiddelde synonymie + http://www.w3.org/ns/lemon/lime + stable + The 'average synonymy' property indicates the average number of lexical entries evoking each lexical concept in the concept set. + Свойство 'средняя синонимия' указывает среднее число словарных единиц, вызывающих каждое лексическое понятие в наборе понятий. + + + + + + + + + + Konzepte + concepts + понятия + conceptos + concepts + concetti + begrippen + The 'concepts' property indicates the number of lexical concepts defined in a concept set or involved in either a LexicalLinkset or ConceptualizationSet. + Свойство 'понятия' указывает количество лексических понятий, определенных в наборе понятий или участвующих либо в LexicalLinkset, либо в ConceptualizationSet. + http://www.w3.org/ns/lemon/lime + stable + + + + + + + + + + + + + + + + + + Konzeptualisierungen + conceptualizations + conceptualizaciones + conceptualisations + concettualizzazioni + conceptualisaties + концептуализации + http://www.w3.org/ns/lemon/lime + stable + The 'conceptualizations' property indicates the number of distinct conceptualizations in a conceptualization set. + Свойство 'концептуализации' указывает на число различных концептуализаций в наборе концептуализаций. + + + + + + + + + + taal + Sprache + language + lengua + langue + lingua + taal + idioma + limbă + språk + язык + The 'language' property indicates the language of a lexicon, a lexical entry, a concept set or a lexicalization set. + Свойство 'язык' указывает язык лексикона, словарной единицы, набора понятий или набора лексикализаций. + http://www.w3.org/ns/lemon/lime + stable + + + + + + + + + + + + + + + + + + + leksikale inskrywing + Lexikoneinträge + lexical entries + entradas léxicas + lexie + entrate lessicali + lexikaal items + entradas lexicas + înregistrari lexicale + lexikoningångar + словарная единица + http://www.w3.org/ns/lemon/lime + stable + The 'lexical entries' property indicates the number of distinct lexical entries contained in a lexicon or lexicalization set. + Свойство 'словарная единица' указывает количество различных словарных единиц, содержащихся в лексиконе или наборе лексикализаций. + + + stable + + + + + + + + + + + + + + + + + leksikaliserings + Lexikalisierungen + lexicalizations + lexicalizaciones + lexicalisations + lessicalizzazioni + lexicalisaties + lexicalizações + lexicalizari + lexikaliseringar + лексикализации + The 'lexicalizations' property indicates the total number of lexicalizations in a lexicalization set, that is the number of unique pairs of lexical entry and denoted ontology element. + Свойство 'лексикализации' указывает общее число лексикализаций в наборе лексикализаций, то есть количество уникальных пар словарных единиц и обозначенного элемента онтологии. + + + stable + + + + + + + + + Links + links + enlaces + liens + link + links + связи + The 'links' property indicates the number of links between concepts in the concept set and entities in the reference dataset. + Свойство 'связи' указывает количество связей между понятиями в наборе понятий и объектами в ссылочном наборе данных. + http://www.w3.org/ns/lemon/lime + stable + + + + + + + + + + Prozentsatz + percentage + porcentaje + pourcentage + percentuale + percentage + процент + The 'percentage' property expresses the percentage of entities in the reference dataset which have at least one lexicalization in a lexicalization set or are linked to a lexical concept in a lexical linkset. + Свойство 'процент' выражает процент объектов в наборе справочных данных, которые имеют хотя бы одну лексикализацию в наборе лексикализации или связаны с лексической концепцией в лексическом наборе ссылок. + http://www.w3.org/ns/lemon/lime + stable + + + + + + + + + + + + + + + + + verwysings + Referenzen + references + referencias + références + riferimenti + referenties + referencias + referințe + referenser + ссылки + The 'references' property indicates the number of distinct ontology or vocabulary elements that are either associated with lexical entries via a lexicalization set or linked to lexical concepts via a lexical link set. + Свойство 'ссылки' указывает количество отдельных онтологий или элементов словаря, которые либо связаны с лексическими элементами через набор лексикализации, либо связаны с лексическими понятиями посредством набора лексической связи. + + + stable + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Konzeptualisierungsatz + conceptualization set + conjuto de conceptualizaciones + banque de concepitalisations + banca concettualizzazioni + verzameling van conceptialisaties + набор концепций + + + + + + 1 + + + + + + + 1 + + + A conceptualization set represents a collection of links between lexical entries in a Lexicon and lexical concepts in a Concept Set they evoke. + Набор концепций представляет собой набор связей между словарными единицами в лексиконе и лексическими понятиями в наборе понятий, которые они вызывают. + http://www.w3.org/ns/lemon/lime + stable + + + + + + + + leksikale skakelstel + Lexikonlinksatz + lexical linkset + conjunto de enlaces + banque de liens lexicals + banca di link lessicali + verzameling van lexicale links + linkset lexical + lexikalisk länkmängd + лексический набор ссылок + + + + + + 1 + + + + + + + 1 + + + + + + + + + A lexical linkset represents a collection of links between a reference dataset and a set of lexical concepts (e.g. synsets of a wordnet). + Лексический набор связей представляет собой набор связей между набором ссылок и набором лексических понятий (например, synsets of wordnet) + + stable + + + + + + + + lexicalization set + набор лексикализаций + + + + + + 1 + + + + + + + + + + + + 1 + + + + + + + 1 + + + A 'lexicalization set' is a dataset that comprises a collection of lexicalizations, that is pairs of lexical entry and corresponding reference in the associated ontology/vocabulary/dataset. + 'Набор лексикализации' - это набор данных, который содержит набор лексикализаций, т.е. пары словарной единицы и соответствующей ссылки в связанной онтологии/словаре/наборе данных. + + stable + + + + + + + + leksikon + Lexikon + lexicon + lexicón + Lexique + Lessico + Lexicon + lexicon + lexikon + лексикон + + + + + + 1 + + + + + + 1 + + + http://www.w3.org/ns/lemon/lime + stable + A lexicon represents a collection of lexical entries for a particular language or domain. + Лексикон представляет собой набор словарных единиц для определенного языка или домена. + + + + + + + + Lexikalisierungmodell + lexicalization model + modelo de lexicalización + modèle de lexicalisation + modello di lessicalizzazione + model van lexicalisatie + модель лексикализации + The 'lexicalization model' property indicates the model used for representing lexical information. Possible values include (but are not limited to) http://www.w3.org/2000/01/rdf-schema# (for the use of rdfs:label), http://www.w3.org/2004/02/skos/core (for the use of skos:pref/alt/hiddenLabel), http://www.w3.org/2008/05/skos-xl (for the use of skosxl:pref/alt/hiddenLabel) and http://www.w3.org/ns/lemon/all for lemon. + Свойство 'модель лексикализации' указывает модель, используемую для представления лексической информации. Возможные значения включают (но не ограничиваются) http://www.w3.org/2000/01/rdf-schema# (for the use of rdfs:label), http://www.w3.org/2004/02/skos/core (for the use of skos:pref/alt/hiddenLabel), http://www.w3.org/2008/05/skos-xl (for the use of skosxl:pref/alt/hiddenLabel) and http://www.w3.org/ns/lemon/all for lemon. + http://www.w3.org/ns/lemon/lime + stable + + + + + + + diff --git a/resources/schemas/external/synsem.xml b/resources/schemas/external/synsem.xml new file mode 100644 index 00000000..1c44368a --- /dev/null +++ b/resources/schemas/external/synsem.xml @@ -0,0 +1,513 @@ + + + + + + + + + + + + + + + +]> + + + + + + 1.1 + 2016-01-10 + 2016-01-10 + A model for the representation of lexical information relative to ontologies. Syntax and semantics module. + CC-Zero + Lexicon Model for Ontologies - Synsem + http://www.w3.org/ns/lemon/synsem# + synsem + + + + + + + + + + + + + + + + + -Version 1.0: depreciation with minor change in metadata for LOV publication +-Version 1.1: creation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + voorwaarde + Bedingung + condition + condición + condition + condizione + voorwaarde + condição + condiție + villkor + состояние + The 'condition' property defines an evaluable constraint that derives from using a certain lexical entry to express a given ontological predicate. + Свойство 'состояние' определяет оценочное ограничение, которое получается из использования определенной словарной единицы для выражения заданного онтологического предиката. + + stable + + + + + + + + + + instansie van + instanz von + Instancia de + Instance de + istanza di + instantie van + é um + instanță a + är en + экземпляр + The 'is a' property represents the single argument of a class or unary predicate. + Свойство 'экземпляр' представляет одиночный аргумент класса или унарный предикат. + + stable + + + + + + + + + merker + Marker + marker + marcador + marqueur + marcatore + merker + marcado + marcator + markör + маркер + The 'marker' property indicates the marker of a syntactic argument; this can be a case marker or some other lexical entry such as a preposition or particle. + Свойство 'маркер' указывает маркер синтаксического аргумента; Это может быть маркер падежа или какая-то другая словарная единица, такая как предлог или частица. + + + stable + + + + + + + + + voorwerp van predikaat + objekt des Prädikats + object of property + complemento de la propiedad + complément de la propriété + oggetto della proprietà + object van predikaat + obiect al proprietății + objekt av predikat + объект свойства + The 'objOfProp' represents the 2nd argument or object of a binary predicate (property) in the ontology. + 'Объект свойства' представляет 2-й аргумент или объект бинарного предиката (свойства) в онтологии. + + + stable + + + + + + + + + + + + + ontologische Korrespondenz + ontological correspondence + correspondencia ontológica + correspondance ontologique + corrispondenza ontologica + ontologische correspondentie + онтологическая переписка + The 'ontoCorrespondence' property binds an argument of a predicate defined in the ontology to a syntactic argument that realizes this predicate argument syntactically. + Свойство 'онтологическая переписка' связывает аргумент предиката, определенного в онтологии, с синтаксическим аргументом, который синтаксически реализует этот предикат. + + + stable + + + + + + + + + + + + + + + + + + + Ontologieabbildung + applicación de l'ontología + application de l'ontologie + mappa de l'ontologia + ontologieafbeelding + отображение онтологии + The 'ontoMapping' property relates an ontology mapping to its corresponding lexical sense. + Свойство 'onMapping' связывает отображение онтологии с соответствующим ему лексическим смыслом. + + stable + + + + + + + + + + predikaatdefinisiegebied + Definitionsbereich des Prädikats + property domain + dominio de la propiedad + ensemble de la propriété + dominio di proprietà + domein van predikaat + domeniul proprietății + relationsdomän + свойство домена + 'Property domain' provides a pragmatic restriction on the domain of the property referred to by this sense. + 'Свойство домена' обеспечивает прагматическое ограничение на область свойства, на которое ссылается этот смысл. + + stable + + + + + + + + + predikaatwaardegebied + Wertemenge des Prädikats + property range + rango de la propiedad + image de la propriété + codominio di proprietà + bereik van predikaat + gama proprietății + relationsräckvidd + диапазон свойства + 'Property domain' provides a pragmatic restriction on the range of the property referred to by this sense. + 'Диапазон свойства' обеспечивает прагматическое ограничение на область диапазона,на которое ссылается этот смысл. + + stable + + + + + + + + + onderwerp van predikaat + Subjekt des Prädikats + subject of property + sujeto de la propiedad + sujet de la propriété + soggetto della proprietà + onderwerp van predikaat + subiectul proprietații + subjekt av predikat + субъект свойства + The 'subjOfProp' property represents the 1st argument or subject of a binary predicate (property) in the ontology. + Свойство 'subjOfProp' представляет 1-й аргумент или субъект бинарного предиката (свойства) в онтологии. + + stable + + + + + + + + + + + + + Subframe + submap + parte del marco + cadre composante + subframe + deelraam + underbetydelse + The 'submap' property relates a (complex) ontological mapping to a set of bindings that together bind the arguments of the involved predicates to a set of syntactic arguments that realize them syntactically. + Свойство 'submap' связывает (сложное) онтологическое отображение с набором привязок, которые вместе связывают аргументы задействованных предикатов с набором синтаксических аргументов, которые реализуют их синтаксически. + + + stable + + + + + + + + + + sintaktiese argument + syntaktisches Argument + syntactic argument + argumento sintáctico + actant syntaxique + argomento sintattico + syntactisch argument + argumento sintatico + argument sintactic + syntaktiskt argument + синтаксический аргумент + The object property synArg relates a syntactic frame to one of its syntactic arguments. + Свойство объекта 'synArg' связывает синтаксический фрейм с одним из его синтаксических аргументов. + + + stable + + + + + + + + + + + sintaktiese dedrag + syntaktisches Verhalten + syntactic behavior + funcionamiento sintáctico + conduite syntaxique + comportamento sintattico + syntactisch optreden + comportamento sintatico + comportament sintactic + syntaktiskt beteende + синтаксическое поведение + The 'syntactic behavior' property relates a lexical entry to one of its syntactic behaviors as captured by a syntactic frame. + Свойство 'синтаксическое поведение' связывает лексическую запись с одним из ее синтаксических типов поведения, захваченных синтаксическим фреймом. + + + stable + + + + + + + + + + + + + + + + + + + + + + + opsioneel + optional + optional + opcional + optionnel + opzionale + optioneel + opcional + facultativ + optionell + опциональный + The 'optional' property indicates whether a syntactic argument is optional, that is, it can be syntactically omitted. + Свойство 'опциональный' указывает, является ли синтаксический аргумент необязательным, то есть его можно синтаксически исключить. + + + + stable + + + + + + + + + + + + + + Ontologieabbildung + ontology mapping + applicación de l'ontología + application de l'ontologie + mappa de l'ontologia + ontologieafbeelding + отображение онтологии + An 'ontology mapping' (OntoMap for short) specifies how a syntactic frame and its syntactic arguments map to a set of concepts and properties in the ontology that together specify the meaning of the syntactic frame. + 'Отображение онтологии' (OntoMap для краткости) определяет, как синтаксический фрейм и его синтаксические аргументы сопоставляются с набором понятий и свойств в онтологии, которые вместе определяют значение синтаксического фрейма. + + stable + + + + + + + + sintaktiese argument + syntaktisches Argument + Syntactic Argument + argumento sintáctico + actant syntaxique + argomento sintattico + syntactisch argument + argumento sintatico + argument sintactic + syntaktiskt argument + синтаксический аргумент + A 'syntactic argument' represents a slot that needs to be filled for a certain syntactic frame to be complete. Syntactic arguments typically realize a certain grammatical function (e.g. subject, direct object, indirect object, prepositional object, etc.). + 'Синтаксический аргумент' представляет собой слот, который необходимо заполнить для получения определенного синтаксического фрейма. Синтаксические аргументы обычно реализуют определенную грамматическую функцию (например, субъект, прямой объект, косвенный объект, предпозиционный объект и т.д.). + + stable + + + + + + + + raam + syntaktisches Frame + Syntactic Frame + marco sintáctico + cadre syntaxique + frame + raam + cadru + ram + синтаксический фрейм + A 'syntactic frame' represents the syntactic behavior of an open class word in terms of the (syntactic) arguments it requires. It essentially describes the so called subcategorization structure of the word in question, in particular the syntactic arguments it requires. + 'Синтаксический фрейм' представляет синтаксическое поведение открытого слова класса в терминах (синтаксических) аргументов, которые ему необходимы. Он по существу описывает так называемую структуру подкатегоризации рассматриваемого слова, в частности синтаксические аргументы, которые он требует. + + stable + + + + + + + diff --git a/src/main/dk/cst/dannet/bootstrap.clj b/src/main/dk/cst/dannet/bootstrap.clj index 3bfe43ff..c5d1beed 100644 --- a/src/main/dk/cst/dannet/bootstrap.clj +++ b/src/main/dk/cst/dannet/bootstrap.clj @@ -15,10 +15,10 @@ (:require [clojure.set :as set] [clojure.java.io :as io] [clojure.string :as str] - [clojure.walk :as walk] [clojure.data.csv :as csv] [ont-app.vocabulary.lstr :refer [->LangStr]] [better-cond.core :as better] + [dk.cst.dannet.hash :as h] [dk.cst.dannet.web.components :as com] [dk.cst.dannet.prefix :as prefix]) (:import [java.util Date])) @@ -26,59 +26,6 @@ ;; TODO: sense mapping seems wrong http://localhost:3456/dannet/external/cor/COR.30123 ;; TODO: weird? http://localhost:3456/dannet/data/synset-47363 -;; Via jpmonettas: https://clojurians.slack.com/archives/C03S1KBA2/p1670838328124429 -;; Copy-pasted from: https://github.com/jpmonettas/hansel/blob/master/src/hansel/instrument/forms.clj#L829-L865 -(defn normalize-gensyms - "When the reader reads things like #(+ % %) it uses a global id to generate symbols, - so everytime will read something different, like : - (fn* [p1__37935#] (+ p1__37935# p1__37935#)) - (fn* [p1__37939#] (+ p1__37939# p1__37939#)) - Normalize symbol can be applied to generate things like : - (fn* [p__0] (+ p__0 p__0)). - Useful for generating stable form hashes." - [form] - (let [psym->id (atom {}) - gensym? (fn [x] - (and (symbol? x) - (re-matches #"^p([\d])__([\d]+)#$" (name x)))) - normal (fn [psym] - (let [ids @psym->id - nsymid (if-let [id (get ids psym)] - id - - (if (empty? ids) - 0 - (inc (apply max (vals ids)))))] - - (swap! psym->id assoc psym nsymid) - - (symbol (str "p__" nsymid))))] - (walk/postwalk - (fn [x] - (if (gensym? x) - (normal x) - x)) - form))) - -(defn hash-form - "Ensure that the sequential `form` coll hashes the same across restarts." - [form] - (hash (mapv str (normalize-gensyms form)))) - -(defmacro def-hashed - "A regular def macro that hashes its own body and attaches this to :hash." - [& [name :as args]] - `(do - (def ~@args) - (alter-meta! #'~name assoc :hash (hash-form (quote ~args))))) - -(defmacro defn-hashed - "A regular defn macro that hashes its own body and attaches this to :hash." - [& [name :as args]] - `(do - (defn ~@args) - (alter-meta! #'~name assoc :hash (hash-form (quote ~args))))) - (defn da [s] (->LangStr s "da")) @@ -102,7 +49,7 @@ "The RDF resource URI for the DanNet/EuroWordNet concepts." (prefix/prefix->rdf-resource 'dnc)) -(def-hashed metadata-triples +(h/def metadata-triples "Metadata for the DanNet dataset is defined here since it doesn't have a associated .ttl file. The Dublin Core Terms NS is used below which supersedes the older DC namespace (see: https://www.dublincore.org/schemas/rdfs/ )." @@ -274,7 +221,7 @@ token (recur tokens)))))) -(defn-hashed examples +(h/defn examples "Convert a `row` from 'synsets.csv' to example key-value pairs." [[synset-id label gloss _ :as row]] (when-let [[_ example-str] (re-find brug gloss)] @@ -406,7 +353,7 @@ (->> (clean-ontological-type "LanguageRepresentation+Artifact+Object") (explode-ontological-type synset))))) -(defn-hashed ->synset-triples +(h/defn ->synset-triples "Convert a `row` from 'synsets.csv' to triples." [[synset-id label gloss ontological-type :as row]] (if (= synset-id "8715") @@ -441,7 +388,7 @@ [inherit :dns/inheritedFrom from] [inherit :dns/inheritedRelation rel]}))) -(defn-hashed ->relation-triples +(h/defn ->relation-triples "Convert a `row` from 'relations.csv' to triples. Note: certain rows are unmapped, so the relation will remain a string!" @@ -490,7 +437,7 @@ (apply str "\"" s "\"" after)) ;; TODO: investigate semantics of ' in input forms of multiword expressions -(defn-hashed ->word-triples +(h/defn ->word-triples "Convert a `row` from 'words.csv' to triples." [[word-id form pos _ :as row]] (when (and (= (count row) 4) @@ -537,7 +484,7 @@ (re-find #"slang" register) (conj [sense :lexinfo/register :lexinfo/slangRegister])))) -(defn-hashed ->sense-triples +(h/defn ->sense-triples "Convert a `row` from 'wordsenses.csv' to triples." [[sense-id word-id synset-id register _ :as row]] (when (and (= (count row) 5) @@ -573,7 +520,7 @@ (get #{"n" "nx" "nxx"} pol) :marl/Negative :else :marl/Neutral)) -(defn-hashed ->sentiment-triples +(h/defn ->sentiment-triples "Convert a `row` from 'sense_polarities.tsv' to Opinion triples. In ~2000 cases a sense-id will be missing (it has the same ID as the word-id). @@ -632,7 +579,7 @@ "kolon" nil}) ;; http://dsn.dk/sprogets-udvikling/sprogteknologi-og-fagsprog/cor# -(defn-hashed ->cor-k-triples +(h/defn ->cor-k-triples "Convert a `row` from the COR-K ID file to triples; assumes that the rows have been preprocessed by 'preprocess-cor-k' beforehand. @@ -672,11 +619,11 @@ rep-id (conj [lexical-form :rdfs/seeAlso full])))) -(defn-hashed ->cor-ext-triples +(h/defn ->cor-ext-triples [[id lemma comment _ _ _ grammar form :as row]] (->cor-k-triples (with-meta [id lemma comment grammar form] (meta row)))) -(defn-hashed ->cor-link-triples +(h/defn ->cor-link-triples [[id word-id sense-id :as row]] (let [[_ cor-ns lemma-id _ _] (re-matches cor-id id) cor-word (cor-uri cor-ns lemma-id) diff --git a/src/main/dk/cst/dannet/db.clj b/src/main/dk/cst/dannet/db.clj index 9c038799..759925a7 100644 --- a/src/main/dk/cst/dannet/db.clj +++ b/src/main/dk/cst/dannet/db.clj @@ -15,7 +15,8 @@ [dk.cst.dannet.db.csv :as db.csv] [dk.cst.dannet.prefix :as prefix] [dk.cst.dannet.web.components :as com] - [dk.cst.dannet.bootstrap :as bootstrap :refer [defn-hashed]] + [dk.cst.dannet.bootstrap :as bootstrap] + [dk.cst.dannet.hash :as h] [dk.cst.dannet.query :as q] [dk.cst.dannet.query.operation :as op] [dk.cst.dannet.transaction :as txn]) @@ -38,9 +39,15 @@ (->> (for [{:keys [alt uri export]} (vals prefix/schemas)] (when-not export (if alt - (if (or (str/starts-with? alt "http://") - (str/starts-with? alt "https://")) + (cond + (= alt :no-schema) + nil + + (or (str/starts-with? alt "http://") + (str/starts-with? alt "https://")) alt + + :else (io/resource alt)) uri))) (filter some?))) @@ -186,7 +193,7 @@ [^Dataset dataset ^String model-uri] (.getGraph (get-model dataset model-uri))) -(defn-hashed add-bootstrap-import! +(h/defn add-bootstrap-import! "Add the `bootstrap-imports` of the old DanNet CSV files to a Jena `dataset`." [dataset bootstrap-imports] (let [{:keys [examples]} (get bootstrap-imports prefix/dn-uri) @@ -286,6 +293,15 @@ dataset)) +(h/defn add-open-english-wordnet! + "Add the Open English WordNet to a Jena `dataset`." + [dataset] + (println "Importing Open English Wordnet...") + (txn/transact-exec dataset + (aristotle/read (get-graph dataset "https://en-word.net/") + "bootstrap/other/english/english-wordnet-2021.ttl")) + (println "Open English Wordnet imported!")) + (defn ->dataset "Get a Dataset object of the given `db-type`. TDB also requires a `db-path`." [db-type & [db-path]] @@ -336,7 +352,9 @@ :or {db-type :in-mem} :as opts}] (let [files (bootstrap-files bootstrap-imports) fn-hashes (conj bootstrap/hashes - (:hash (meta #'add-bootstrap-import!))) + (:hash (meta #'add-bootstrap-import!)) + (:hash (meta #'add-open-english-wordnet!)) + (hash prefix/schemas)) ;; Undo potentially negative number by bit-shifting. files-hash (pos-hash files) bootstrap-hash (pos-hash fn-hashes) @@ -354,6 +372,7 @@ (do (println "Data input has changed -- rebuilding database...") (add-bootstrap-import! dataset bootstrap-imports) + (add-open-english-wordnet! dataset) (println new-entry) (spit log-path (str new-entry "\n----\n") :append true))) (println "WARNING: no imports!")) diff --git a/src/main/dk/cst/dannet/hash.clj b/src/main/dk/cst/dannet/hash.clj new file mode 100644 index 00000000..e893b503 --- /dev/null +++ b/src/main/dk/cst/dannet/hash.clj @@ -0,0 +1,64 @@ +(ns dk.cst.dannet.hash + "Functions for hashing program data; used to invoke database rebuilds. + + The :hash key of the metadata attached to any hashed def/defn forms can be + checked at runtime. If this hash differs from the last recorded hash, the form + must have changed in some way. + + The key functions and data in DanNet have been decorated with hashes. + These hashes are checked when instantiating an instance of a DanNet database." + (:require [clojure.walk :as walk]) + (:refer-clojure :exclude [defn])) + +;; Via jpmonettas: https://clojurians.slack.com/archives/C03S1KBA2/p1670838328124429 +;; Copy-pasted from: https://github.com/jpmonettas/hansel/blob/master/src/hansel/instrument/forms.clj#L829-L865 +(clojure.core/defn normalize-gensyms + "When the reader reads things like #(+ % %) it uses a global id to generate symbols, + so everytime will read something different, like : + (fn* [p1__37935#] (+ p1__37935# p1__37935#)) + (fn* [p1__37939#] (+ p1__37939# p1__37939#)) + Normalize symbol can be applied to generate things like : + (fn* [p__0] (+ p__0 p__0)). + Useful for generating stable form hashes." + [form] + (let [psym->id (atom {}) + gensym? (fn [x] + (and (symbol? x) + (re-matches #"^p([\d])__([\d]+)#$" (name x)))) + normal (fn [psym] + (let [ids @psym->id + nsymid (if-let [id (get ids psym)] + id + + (if (empty? ids) + 0 + (inc (apply max (vals ids)))))] + + (swap! psym->id assoc psym nsymid) + + (symbol (str "p__" nsymid))))] + (walk/postwalk + (fn [x] + (if (gensym? x) + (normal x) + x)) + form))) + +(clojure.core/defn hash-form + "Ensure that the sequential `form` coll hashes the same across restarts." + [form] + (hash (mapv str (normalize-gensyms form)))) + +(defmacro def + "A regular def macro that hashes its own body and attaches this to :hash." + [& [name :as args]] + `(do + (def ~@args) + (alter-meta! #'~name assoc :hash (hash-form (quote ~args))))) + +(defmacro defn + "A regular defn macro that hashes its own body and attaches this to :hash." + [& [name :as args]] + `(do + (clojure.core/defn ~@args) + (alter-meta! #'~name assoc :hash (hash-form (quote ~args))))) diff --git a/src/main/dk/cst/dannet/prefix.cljc b/src/main/dk/cst/dannet/prefix.cljc index fbf82c57..55ca3872 100644 --- a/src/main/dk/cst/dannet/prefix.cljc +++ b/src/main/dk/cst/dannet/prefix.cljc @@ -1,9 +1,9 @@ (ns dk.cst.dannet.prefix "Prefix registration for the various schemas used by DanNet." (:require #?(:clj [arachne.aristotle.registry :as reg]) + [clojure.string :as str] [ont-app.vocabulary.core :as voc] - [reitit.impl :refer [url-encode]] ; CLJC url-encode - [clojure.string :as str])) + [reitit.impl :refer [url-encode]])) ; CLJC url-encode ;; NOTE: you must also edit the DanNet schema files if changing this! (def dannet-root @@ -13,70 +13,86 @@ "http://www.wordnet.dk/download/dannet/") (def schemas - {'rdf {:uri "http://www.w3.org/1999/02/22-rdf-syntax-ns#" - :alt "schemas/external/rdf.ttl"} - 'rdfs {:uri "http://www.w3.org/2000/01/rdf-schema#" - :alt "schemas/external/rdfs.ttl"} - 'owl {:uri "http://www.w3.org/2002/07/owl#" - :alt "schemas/external/owl.ttl"} - 'wn {:uri "https://globalwordnet.github.io/schemas/wn#" ; https official - :alt "schemas/external/wn-lemon-1.2.ttl"} - 'svs {:uri "http://www.w3.org/2003/06/sw-vocab-status/ns#" - :alt "schemas/external/svs.xml"} - 'ontolex {:uri "http://www.w3.org/ns/lemon/ontolex#" - :alt "schemas/external/ontolex.xml"} - 'lemon {:uri "http://lemon-model.net/lemon#" - :alt "schemas/external/lemon-model.ttl"} - 'semowl {:uri "http://www.ontologydesignpatterns.org/cp/owl/semiotics.owl#" - :alt "schemas/external/semiotics.owl"} - 'skos {:uri "http://www.w3.org/2004/02/skos/core#" - :alt "schemas/external/skos.rdf"} - 'lexinfo {:uri "http://www.lexinfo.net/ontology/3.0/lexinfo#" - :alt "schemas/external/lexinfo-3.0.owl"} - 'marl {:uri "http://www.gsi.upm.es/ontologies/marl/ns#" - :alt "schemas/external/marl.n3"} - 'olia {:uri "http://purl.org/olia/olia.owl#" - :alt "schemas/external/olia.owl"} + {'rdf {:uri "http://www.w3.org/1999/02/22-rdf-syntax-ns#" + :alt "schemas/external/rdf.ttl"} + 'rdfs {:uri "http://www.w3.org/2000/01/rdf-schema#" + :alt "schemas/external/rdfs.ttl"} + 'owl {:uri "http://www.w3.org/2002/07/owl#" + :alt "schemas/external/owl.ttl"} + 'wn {:uri "https://globalwordnet.github.io/schemas/wn#" ; https official + :alt "schemas/external/wn-lemon-1.2.ttl"} + 'svs {:uri "http://www.w3.org/2003/06/sw-vocab-status/ns#" + :alt "schemas/external/svs.xml"} + 'ontolex {:uri "http://www.w3.org/ns/lemon/ontolex#" + :alt "schemas/external/ontolex.xml"} + 'lemon {:uri "http://lemon-model.net/lemon#" + :alt "schemas/external/lemon-model.ttl"} + 'semowl {:uri "http://www.ontologydesignpatterns.org/cp/owl/semiotics.owl#" + :alt "schemas/external/semiotics.owl"} + 'skos {:uri "http://www.w3.org/2004/02/skos/core#" + :alt "schemas/external/skos.rdf"} + 'lexinfo {:uri "http://www.lexinfo.net/ontology/3.0/lexinfo#" + :alt "schemas/external/lexinfo-3.0.owl"} + 'marl {:uri "http://www.gsi.upm.es/ontologies/marl/ns#" + :alt "schemas/external/marl.n3"} + 'olia {:uri "http://purl.org/olia/olia.owl#" + :alt "schemas/external/olia.owl"} ;; Metadata-related namespaces. - 'dcat {:uri "http://www.w3.org/ns/dcat#" - :alt "schemas/external/dcat2.ttl"} - 'vann {:uri "http://purl.org/vocab/vann/" - :alt "schemas/external/vann.ttl"} - 'foaf {:uri "http://xmlns.com/foaf/0.1/" - :alt "schemas/external/foaf.rdf"} - 'dc {:uri "http://purl.org/dc/terms/" - :alt "schemas/external/dublin_core_terms.ttl"} - 'dc11 {:uri "http://purl.org/dc/elements/1.1/" - :alt "schemas/external/dublin_core_elements.ttl"} - 'cc {:uri "http://creativecommons.org/ns#" - :alt "schemas/external/cc.rdf"} + 'dcat {:uri "http://www.w3.org/ns/dcat#" + :alt "schemas/external/dcat2.ttl"} + 'vann {:uri "http://purl.org/vocab/vann/" + :alt "schemas/external/vann.ttl"} + 'foaf {:uri "http://xmlns.com/foaf/0.1/" + :alt "schemas/external/foaf.rdf"} + 'dc {:uri "http://purl.org/dc/terms/" + :alt "schemas/external/dublin_core_terms.ttl"} + 'dc11 {:uri "http://purl.org/dc/elements/1.1/" + :alt "schemas/external/dublin_core_elements.ttl"} + 'cc {:uri "http://creativecommons.org/ns#" + :alt "schemas/external/cc.rdf"} + + ;; Used by Open English WordNet + 'ili {:uri "http://ili.globalwordnet.org/ili/" + :alt :no-schema} + 'lime {:uri "http://www.w3.org/ns/lemon/lime#" + :alt "schemas/external/lime.xml"} + 'schema {:uri "http://schema.org/" + :alt :no-schema} + 'synsem {:uri "http://www.w3.org/ns/lemon/synsem#" + :alt "schemas/external/synsem.xml"} + 'oewnlemma {:uri "https://en-word.net/lemma/" + :alt :no-schema} + 'oewnid {:uri "https://en-word.net/id/" + :alt :no-schema} ;; The COR namespace - 'cor {:uri "http://ordregister.dk/id/COR." - :export #{'dn 'cor - 'rdf 'rdfs 'owl - 'ontolex 'skos 'lexinfo}} + 'cor {:uri "http://ordregister.dk/id/COR." + :export #{'dn 'cor + 'rdf 'rdfs 'owl + 'ontolex 'skos 'lexinfo}} ;; Sentiment data (unofficial) TODO - 'senti {:uri "http://example.com" - :export #{'dn 'dns 'marl}} + 'senti {:uri "http://example.com" + :export #{'dn 'dns 'marl}} ;; The three internal DanNet namespaces. - 'dn {:uri (str dannet-root "data/") - :export #{'dn 'dnc 'dns - 'rdf 'rdfs 'owl - 'wn 'ontolex 'skos 'lexinfo - 'dcat 'vann 'foaf 'dc}} + 'dn {:uri (str dannet-root "data/") + :export #{'dn 'dnc 'dns + 'rdf 'rdfs 'owl + 'wn 'ontolex 'skos 'lexinfo + 'dcat 'vann 'foaf 'dc}} - 'dnc {:uri (str dannet-root "concepts/") - :alt "schemas/internal/dannet-concepts-2022.ttl"} - 'dns {:uri (str dannet-root "schema/") - :alt "schemas/internal/dannet-schema-2022.ttl"} + 'dnc {:uri (str dannet-root "concepts/") + :alt "schemas/internal/dannet-concepts-2022.ttl"} + 'dns {:uri (str dannet-root "schema/") + :alt "schemas/internal/dannet-schema-2022.ttl"} ;; Various en->da translations included as additional data. - 'tr {:uri (str dannet-root "translations/") - :alt "schemas/internal/dannet-translations-2022.ttl"}}) + 'tr {:uri (str dannet-root "translations/") + :alt "schemas/internal/dannet-translations-2022.ttl"}}) + + (def internal-prefixes #{'dn 'dnc 'dns}) diff --git a/src/main/dk/cst/dannet/web/components.cljc b/src/main/dk/cst/dannet/web/components.cljc index 89a7f332..29558e73 100644 --- a/src/main/dk/cst/dannet/web/components.cljc +++ b/src/main/dk/cst/dannet/web/components.cljc @@ -305,7 +305,8 @@ [{:keys [languages k->label] :as opts}] (fn [item] (let [k (if (map-entry? item) (first item) item)] - [(str (i18n/select-label languages (get k->label k))) item]))) + [(str (i18n/select-label languages (get k->label k))) + (str item)]))) (rum/defc list-item "A list item element of a 'list-cell'."