From b7e6b84174793acf422249850afac3840f4bc95f Mon Sep 17 00:00:00 2001 From: Gregor Middell Date: Wed, 10 Jul 2024 14:52:53 +0200 Subject: [PATCH] Sets up project --- .dir-locals.el | 7 + .dockerignore | 4 + .github/workflows/test.yml | 25 ++++ .gitignore | 6 + Dockerfile | 12 ++ LICENSE | 165 +++++++++++++++++++++ README.md | 18 +++ compose.yml | 14 ++ deps.edn | 23 +++ dev/user.clj | 40 +++++ resources/corpus-metadata.csv | 12 ++ src/ddc/client.clj | 139 ++++++++++++++++++ src/ddc/env.clj | 52 +++++++ src/ddc/fcs.clj | 268 ++++++++++++++++++++++++++++++++++ src/ddc/query.clj | 237 ++++++++++++++++++++++++++++++ test/ddc/query_test.clj | 89 +++++++++++ tests.edn | 7 + 17 files changed, 1118 insertions(+) create mode 100644 .dir-locals.el create mode 100644 .dockerignore create mode 100644 .github/workflows/test.yml create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 LICENSE create mode 100644 README.md create mode 100644 compose.yml create mode 100644 deps.edn create mode 100644 dev/user.clj create mode 100644 resources/corpus-metadata.csv create mode 100644 src/ddc/client.clj create mode 100644 src/ddc/env.clj create mode 100644 src/ddc/fcs.clj create mode 100644 src/ddc/query.clj create mode 100644 test/ddc/query_test.clj create mode 100644 tests.edn diff --git a/.dir-locals.el b/.dir-locals.el new file mode 100644 index 0000000..693f26e --- /dev/null +++ b/.dir-locals.el @@ -0,0 +1,7 @@ +;;; Directory Local Variables +;;; For more information see (info "(emacs) Directory Variables") + +((clojure-mode . ((cider-preferred-build-tool . clojure-cli) + (cider-clojure-cli-aliases . ":dev:test") + (cider-ns-refresh-before-fn . "user/halt") + (cider-ns-refresh-after-fn . "user/go")))) diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..c43254f --- /dev/null +++ b/.dockerignore @@ -0,0 +1,4 @@ +* +!deps.edn +!resources/ +!src/ diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..31d73e4 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,25 @@ +name: Tests + +on: [push] + +jobs: + test: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4.1.7 + + - name: Prepare java + uses: actions/setup-java@v4.2.1 + with: + distribution: 'temurin' + java-version: '21' + + - name: Install clojure tools-deps + uses: DeLaGuardo/setup-clojure@12.5 + with: + cli: 1.11.2.1446 + + - name: Execute tests + run: clojure -X:test + shell: bash diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea0493c --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +.env + +.nrepl-port +.cpcache/ + +*.temp diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..447824c --- /dev/null +++ b/Dockerfile @@ -0,0 +1,12 @@ +FROM clojure:temurin-21-alpine + +RUN mkdir -p /ddc-fcs +WORKDIR /ddc-fcs + +COPY deps.edn /ddc-fcs/ +RUN clojure -P + +COPY ./ /ddc-fcs + +# "-XX:+UseContainerSupport", "-XX:MaxRAMPercentage=90" +ENTRYPOINT ["clojure", "-X", "ddc.fcs/serve"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0a04128 --- /dev/null +++ b/LICENSE @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/README.md b/README.md new file mode 100644 index 0000000..7c9971e --- /dev/null +++ b/README.md @@ -0,0 +1,18 @@ +# DDC-FCS + +_API gateway connecting ZDL's linguistic corpora to the Federated +Content Search (FCS) of CLARIN and Text+_ + +## Prerequisites + +* [Docker](https://docs.docker.com/get-docker/): The API gateway is + implemented in Clojure and is deployed as a Docker container. + +## Deployment + + DOCKER_HOST="ssh://clarin.bbaw.de" DDC_FCS_RESTART=unless-stopped\ + docker compose up --build -d + +## License + +This project is licensed under the GNU Lesser General Public License v3.0. diff --git a/compose.yml b/compose.yml new file mode 100644 index 0000000..a716772 --- /dev/null +++ b/compose.yml @@ -0,0 +1,14 @@ +services: + ddc-fcs: + image: ${CI_REGISTRY_IMAGE:-gremid}/ddc-fcs:${CI_COMMIT_SHORT_SHA:-latest} + build: + context: . + restart: ${DDC_FCS_RESTART:-no} + environment: + - "DDC_FCS_HTTP_PROTOCOL=https" + - "DDC_FCS_HTTP_HOST=clarin.bbaw.de" + - "DDC_FCS_HTTP_PORT=443" + - "DDC_FCS_HTTP_CONTEXT_PATH=/fcs" + - "DDC_FCS_HTTP_SERVER_PORT=9090" + ports: + - "9090:9090" diff --git a/deps.edn b/deps.edn new file mode 100644 index 0000000..13dabc3 --- /dev/null +++ b/deps.edn @@ -0,0 +1,23 @@ +{:paths ["src" "resources"] + :deps {org.clojure/clojure {:mvn/version "1.11.1"} + org.clojure/data.csv {:mvn/version "1.1.0"} + com.github.igrishaev/virtuoso {:mvn/version "0.1.0"} + hato/hato {:mvn/version "0.9.0"} + com.cnuernber/charred {:mvn/version "1.034"} + lambdaisland/uri {:mvn/version "1.16.134"} + io.github.cdimascio/dotenv-java {:mvn/version "3.0.0"} + babashka/fs {:mvn/version "0.5.21"} + io.github.gremid/clj-xml {:git/sha "6e0c723aea0f282219daa3e603acfe07011cfeb6"} + com.taoensso/timbre {:mvn/version "6.3.1"} + com.fzakaria/slf4j-timbre {:mvn/version "0.4.1"} + org.eclipse.jetty.ee8/jetty-ee8-servlet {:mvn/version "12.0.10"} + eu.clarin.sru.fcs/fcs-simple-endpoint {:mvn/version "1.7.0"}} + :aliases {:dev {:extra-paths ["dev"] + :extra-deps {org.clojure/tools.namespace {:mvn/version "1.4.4"}}} + :test {:extra-paths ["test"] + :extra-deps {lambdaisland/kaocha {:mvn/version "1.87.1366"}} + :exec-fn kaocha.runner/exec-fn}} + :mvn/repos {"clarin" {:url "https://nexus.clarin.eu/content/repositories/Clarin" + :snapshots {:enabled false}} + "clarin-snapshots" {:url "https://nexus.clarin.eu/content/repositories/clarin-snapshot" + :snapshots {:enabled true}}}} diff --git a/dev/user.clj b/dev/user.clj new file mode 100644 index 0000000..5519ff4 --- /dev/null +++ b/dev/user.clj @@ -0,0 +1,40 @@ +(ns user + (:require + [clojure.tools.namespace.repl :as repl :refer [set-refresh-dirs]] + [ddc.fcs])) + +(set-refresh-dirs "dev" "src" "test") + +(defn start! + [] + (let [stop-server! (ddc.fcs/start!)] + (fn [] (stop-server!)))) + +(def stop! + nil) + +(defn go + [] + (alter-var-root #'stop! (constantly (start!)))) + +(defn halt + [] + (when stop! + (stop!) + (alter-var-root #'stop! (constantly nil)))) + +(defn reset + [] + (halt) + (repl/refresh :after 'user/go)) + +(defn reset-all + [] + (halt) + (repl/refresh-all :after 'user/go)) + +(comment + (go) + (halt) + (reset) + (reset-all)) diff --git a/resources/corpus-metadata.csv b/resources/corpus-metadata.csv new file mode 100644 index 0000000..921e0c7 --- /dev/null +++ b/resources/corpus-metadata.csv @@ -0,0 +1,12 @@ +Corpus,PID,URL,Title (de),Title (en),Author (de),Author (en),Description (de),Description (en) +bz,http://hdl.handle.net/11858/00-203C-0000-0029-C1C8-D,https://www.dwds.de/r?corpus=bz,Berliner Zeitung (1994–2005),Berliner Zeitung (1994–2005),"DWDS + CLARIN-D, Berlin-Brandenburgische Akademie der Wissenschaften","DWDS + CLARIN-D, Berlin-Brandenburg Academy of Sciences and Humanities",Berliner Zeitung (1994–2005) – Zeitungsarchiv an der Berlin-Brandenburgische Akademie der Wissenschaften.,Berliner Zeitung (1994–2005) – Newspaper archive at the Berlin-Brandenburg Academy of Sciences and Humanities. +c4,http://hdl.handle.net/11858/00-203C-0000-0023-EAB2-D,https://www.korpus-c4.org,Korpus C4,Corpus C4,"Deutsches Textarchiv + CLARIN-D, Berlin-Brandenburgische Akademie der Wissenschaften","German Text Archive + CLARIN-D, Berlin-Brandenburg Academy of Sciences and Humanities","Gemeinsames Korpus des Digitalen Wörterbuchs der deutschen Sprache des 20. Jahrhunderts (DWDS), des Austrian Academy Corpus (AAC), des Korpus Südtirol und des Schweizer Textkorpus (CHTK).","Joint text corpus drawn from the Digital Dictionary of 20th-Century German (DWDS), the Austrian Academy Corpus (AAC), the Korpus Südtirol, and the Schweizer Textkorpus (CHTK)." +dingler,http://hdl.handle.net/11858/00-203C-0000-0023-8325-E,http://www.dinglr.de,Polytechnisches Journal (Dingler Online),Polytechnical Journal (Dingler Online),"Deutsches Textarchiv + CLARIN-D, Berlin-Brandenburgische Akademie der Wissenschaften","German Text Archive + CLARIN-D, Berlin-Brandenburg Academy of Sciences and Humanities",Textbestand des Polytechnisches Journals (Dingler Online) an der BBAW CLARIN-D Service Centre.,Text corpus of the Polytechnical Journal (Dingler Online) at the BBAW CLARIN-D Service Centre. +dta,http://hdl.handle.net/11858/00-203C-0000-0023-8324-0,https://www.deutschestextarchiv.de,Deutsches Textarchiv (DTA),German Text Archive (DTA),"Deutsches Textarchiv + CLARIN-D, Berlin-Brandenburgische Akademie der Wissenschaften","German Text Archive + CLARIN-D, Berlin-Brandenburg Academy of Sciences and Humanities",Deutsches Textarchiv (DTA) – Grundlage für ein Referenzkorpus der neuhochdeutschen Sprache.,German Text Archive (DTA) – Basis for a reference corpus of the New High German language. +grenzboten,http://hdl.handle.net/11858/00-203C-0000-002E-1DFC-8,https://brema.suub.uni-bremen.de/grenzboten/,Die Grenzboten,Die Grenzboten (“Messengers from the Borders”),"Staats- und Universitätsbibliothek Bremen, Deutsches Textarchiv + CLARIN-D, Berlin-Brandenburgische Akademie der Wissenschaften","State and University Library Bremen, German Text Archive + CLARIN-D, Berlin-Brandenburg Academy of Sciences and Humanities",Die Grenzboten (1841–1922) – digitalisierte Zeitschrift aus dem Bestand der Staats- und Universitätsbibliothek Bremen.,Die Grenzboten (“Messengers from the Borders”) (1841–1922) – digitized periodical from the archives of the State and University Library Bremen. +ibk_dchat,http://hdl.handle.net/11858/00-203C-0000-002E-1DFD-6,https://www.chatkorpus.tu-dortmund.de,Dortmunder Chat-Korpus,Dortmund Chat Corpus,"Textkorpus erstellt von Prof. Dr. Angelika Storrer und Dr. Michael Beißwenger, Institut für deutsche Sprache und Literatur der Technischen Universität Dortmund. Korpusindex und FCS-Endpoint bereitgestellt vom Deutschen Textarchiv und CLARIN-D, Berlin-Brandenburgische Akademie der Wissenschaften.","Corpus compiled by Prof. Dr. Angelika Storrer and Dr. Michael Beißwenger, Institut for the German Language and Technical University Dortmund. Corpus index and FCS endpoint provided by the German Text Archive and CLARIN-D, Berlin-Brandenburg Academy of Sciences and Humanities.",Dortmunder Chat-Korpus – Grundlage und Hilfsmittel für sprachwissenschaftliche Untersuchungen zur synchronen internetbasierten Kommunikation.,Dortmund Chat Corpus – Basis for and aid to linguistic investigations of synchronic internet-based communication. +kern,http://hdl.handle.net/11858/00-203C-0000-0029-C1CA-9,https://www.dwds.de/r?corpus=kern,DWDS-Kernkorpus,DWDS-Kernkorpus,"DWDS + CLARIN-D, Berlin-Brandenburgische Akademie der Wissenschaften","DWDS + CLARIN-D, Berlin-Brandenburg Academy of Sciences and Humanities","Das DWDS-Kernkorpus des 20. Jahrhunderts an der Berlin-Brandenburgischen Akademie der Wissenschaften ist ein zeitlich und nach Textsorten (Belletristik, Gebrauchsliteratur, Wissenschaft, journalistische Prosa) ausgewogenes Korpus des gesamten 20. Jahrhunderts. Textgrundlage sind Werke der Literatur, wissenschaftliche Texte, Gebrauchstexte und Zeitungstexte, die in einem ausgewogenen Verhältnis zueinander stehen.",DWDS-Kernkorpus – balanced corpus of 20th-century German at the Berlin-Brandenburg Academy of Sciences and Humanities. +rem,http://hdl.handle.net/11858/00-203C-0000-002E-1DFB-A,https://www.deutschestextarchiv.de/rem/,Referenzkorpus Mittelhochdeutsch (ReM),Reference Corpus of Middle High German (ReM),"Textkorpus erstellt und annotiert von Thomas Klein, Klaus-Peter Wegera, Stefanie Dipper, und Claudia Wich-Reif. Korpusindex und FCS-Endpoint bereitgestellt vom Deutschen Textarchiv und CLARIN-D, Berlin-Brandenburgische Akademie der Wissenschaften.","Corpus compiled and annotated by Thomas Klein, Klaus-Peter Wegera, Stefanie Dipper, und Claudia Wich-Reif. Corpus index and FCS endpoint provided by the German Text Archive and CLARIN-D, Berlin-Brandenburg Academy of Sciences and Humanities.",Referenzkorpus Mittelhochdeutsch (ReM) – ein Korpus diplomatisch transkribierter und annotierter Texte des Mittelhochdeutschen (1050–1350).,Reference Corpus of Middle High German (ReM) – a corpus of diplomatically transcribed and annotated texts from Middle High German (1050–1350). +tsp,http://hdl.handle.net/11858/00-203C-0000-0029-C1C9-B,https://www.dwds.de/r?corpus=tsp,Tagesspiegel,Tagesspiegel,"DWDS + CLARIN-D, Berlin-Brandenburgische Akademie der Wissenschaften","DWDS + CLARIN-D, Berlin-Brandenburg Academy of Sciences and Humanities",Tagesspiegel – Zeitungsarchiv an der Berlin-Brandenburgischen Akademie der Wissenschaften.,Tagesspiegel – Newspaper archive at the Berlin-Brandenburg Academy of Sciences and Humanities. +dwdsxl,http://hdl.handle.net/21.11120/0000-000F-D5E7-C,https://www.dwds.de/d/korpora/dwdsxl,DWDS – Gegenwartskorpora,DWDS – Contemporary Corpora,"DWDS, Berlin-Brandenburgische Akademie der Wissenschaften","DWDS, Berlin-Brandenburg Academy of Sciences and Humanities",Sammlung gegenwartssprachlicher Textkorpora an der Berlin-Brandenburgischen Akademie der Wissenschaften,Collection of contemporary text corpora at the Berlin-Brandenburg Academy of Sciences and Humanities +dtaxl,http://hdl.handle.net/21.11120/0000-000F-D5EB-8,https://www.dwds.de/d/korpora/dtaxl,DWDS – Historische Korpora,DWDS – Historical Corpora,"DWDS, Berlin-Brandenburgische Akademie der Wissenschaften","DWDS, Berlin-Brandenburg Academy of Sciences and Humanities",Sammlung historischer Textkorpora an der Berlin-Brandenburgischen Akademie der Wissenschaften,Collection of historical text corpora at the Berlin-Brandenburg Academy of Sciences and Humanities diff --git a/src/ddc/client.clj b/src/ddc/client.clj new file mode 100644 index 0000000..8b722bf --- /dev/null +++ b/src/ddc/client.clj @@ -0,0 +1,139 @@ +(ns ddc.client + (:require + [charred.api :as charred] + [clojure.data.csv :as csv] + [clojure.string :as str] + [ddc.env :as env] + [hato.client :as hc] + [taoensso.timbre :as log] + [virtuoso.core :as v] + [clojure.java.io :as io]) + (:import + (java.io DataInputStream InputStream OutputStream) + (java.net Socket) + (java.nio ByteBuffer ByteOrder) + (java.nio.charset Charset))) + +(def ^Charset charset + (Charset/forName "UTF-8")) + +(defn write-str + [^OutputStream out ^String s] + (let [payload (. s (getBytes charset)) + len (count payload)] + (. out (write (.. (ByteBuffer/allocate 4) + (order ByteOrder/LITTLE_ENDIAN) + (putInt (unchecked-int len)) + (array)))) + (. out (write payload)) + (. out (flush)))) + +(defn read-str + [^InputStream in] + (let [in (DataInputStream. in) + len (byte-array 4)] + (.readFully in len) + (let [len (.. (ByteBuffer/wrap len) + (order ByteOrder/LITTLE_ENDIAN) + (getInt)) + s (byte-array len)] + (.readFully in s) + (String. s charset)))) + +(defn request + [[host port :as endpoint] cmd] + (try + (log/tracef "? [%15s %5d/tcp] '%s'" host port cmd) + (with-open [socket (Socket. ^String host (int port)) + output (.getOutputStream socket) + input (.getInputStream socket)] + (write-str output cmd) + (let [result (read-str input)] + (log/tracef ". [%15s %5d/tcp -> %,15d chars] '%s'" + host port (count result) cmd) + (charred/read-json result))) + (catch Throwable t + (throw (ex-info "DDC request error" {:endpoint endpoint :cmd cmd} t))))) + +(defn query + [endpoint q & {:keys [offset page-size timeout] + :or {offset 0 page-size 1000 timeout 30}}] + (assert (not-empty q) "No query (q) given") + (let [cmd (->> (str/join " " [offset page-size timeout]) + (vector "run_query Distributed" q "json") + (str/join \)) + response (request endpoint cmd) + total (get response "nhits_" 0) + results (get response "hits_")] + (when (seq results) + (lazy-cat + (let [meta {:endpoint endpoint :total total}] + (map-indexed #(with-meta %2 (assoc meta :offset (+ offset %1))) results)) + (let [offset (+ offset (count results))] + (when (< offset total) + (query endpoint q + :offset offset + :page-size page-size + :timeout timeout))))))) + +(comment + (request ["data.dwds.de" 52170] "info") + (take 1 (query ["tuvok.bbaw.de" 60260] "Pudel" :page-size 1)) + (take 2 (query ["data.dwds.de" 52170] "Hochkaräter #CNTXT 1" :page-size 2))) + +(def metadata-fields + [:pid :url :title-de :title-en :author-de :author-en :desc-de :desc-en]) + +(def metadata + (with-open [r (io/reader (io/resource "corpus-metadata.csv"))] + (->> (csv/read-csv r) + (drop 1) + (map (fn [[corpus & metadata]] [corpus (zipmap metadata-fields metadata)])) + (into (sorted-map))))) + +(def endpoints + (as-> (hc/request env/dstar-endpoint-request) $ + (charred/read-json (get $ :body) :key-fn keyword) + (into + (sorted-map) + (mapcat (fn [{:keys [host port corpus]}] + (when (metadata corpus) + (list [corpus [host (parse-long port)]])))) + $))) + +(log/infof "Retrieved %d endpoint(s) from %s" + (count endpoints) + (env/dstar-endpoint-request :url)) + +(def corpora + (into (sorted-map) + (mapv vector + (keys endpoints) + (v/pmap! #(request % "info") + (vals endpoints))))) + +(def indices + (into (sorted-map) + (mapv vector + (keys corpora) + (for [info (vals corpora)] + (->> (tree-seq #(% "corpora") #(% "corpora") info) + (mapcat #(map (fn [{k "shortname"}] k) (% "indices"))) + (remove nil?) + (into (sorted-set))))))) + +(defn corpus-tokens + [corpus-info] + (->> + corpus-info + (tree-seq #(get % "corpora") #(get % "corpora")) + (filter #(get % "indexed")) + (map #(get % "ntokens")) + (reduce +))) + +(doseq [[corpus corpus-info] corpora :let [[host port] (endpoints corpus)]] + (log/infof "DDC endpoint %s @ %s:%d – %,d token(s)" + corpus host port (corpus-tokens corpus-info))) + +(comment + (indices "dta")) diff --git a/src/ddc/env.clj b/src/ddc/env.clj new file mode 100644 index 0000000..9fc2a83 --- /dev/null +++ b/src/ddc/env.clj @@ -0,0 +1,52 @@ +(ns ddc.env + (:import + (io.github.cdimascio.dotenv Dotenv))) + +(def ^Dotenv dot-env + (.. Dotenv (configure) (ignoreIfMissing) (load))) + +(defn get-env + ([k] + (get-env k nil)) + ([^String k df] + (let [k (str "DDC_FCS_" k)] + (or (System/getenv k) (.get dot-env k) df)))) + +(def debug? + (some? (not-empty (get-env "DEBUG")))) + +(def dstar-endpoint-index + (get-env "DSTAR_INDEX" "https://ddc.dwds.de/dstar/")) + +(def dstar-endpoint-user + (get-env "DSTAR_USER")) + +(def dstar-endpoint-password + (get-env "DSTAR_PASSWORD")) + +(def dstar-endpoint-credentials + (when (and dstar-endpoint-user dstar-endpoint-password) + {:basic-auth {:user dstar-endpoint-user + :pass dstar-endpoint-password}})) + +(def dstar-endpoint-request + (cond-> {:method :get + :url dstar-endpoint-index + :query-params {"f" "json"}} + dstar-endpoint-credentials (-> (update :url str "intern.perl") + (merge dstar-endpoint-credentials)))) + +(def http-protocol + (get-env "HTTP_PROTOCOL" "http")) + +(def http-host + (get-env "HTTP_HOST" "localhost")) + +(def http-port + (get-env "HTTP_PORT" "8080")) + +(def http-context-path + (get-env "HTTP_CONTEXT_PATH" "")) + +(def http-server-port + (parse-long (get-env "HTTP_SERVER_PORT" http-port))) diff --git a/src/ddc/fcs.clj b/src/ddc/fcs.clj new file mode 100644 index 0000000..ea38609 --- /dev/null +++ b/src/ddc/fcs.clj @@ -0,0 +1,268 @@ +(ns ddc.fcs + (:require + [babashka.fs :as fs] + [clojure.java.io :as io] + [ddc.client :as client] + [ddc.env :as env] + [ddc.query :as query] + [gremid.xml :as gx] + [lambdaisland.uri :as uri] + [taoensso.timbre :as log]) + (:import + (eu.clarin.sru.server SRUConstants SRUException SRUQueryParserRegistry$Builder SRUResultCountPrecision SRUSearchResultSet SRUServer SRUServerConfig) + (eu.clarin.sru.server.fcs AdvancedDataViewWriter AdvancedDataViewWriter$Unit DataView DataView$DeliveryPolicy Layer Layer$ContentEncoding ResourceInfo SimpleEndpointSearchEngineBase XMLStreamWriterHelper) + (eu.clarin.sru.server.fcs.utils SimpleEndpointDescription) + (java.net URI) + (javax.servlet.http HttpServlet) + (org.eclipse.jetty.ee8.servlet ServletContextHandler ServletHolder) + (org.eclipse.jetty.server Server ServerConnector))) + +(log/handle-uncaught-jvm-exceptions!) +(log/merge-config! + {:min-level [["eu.clarin.sru.server.SRUServer" :warn] + ["*"(if env/debug? :debug :info)]] + :appenders {:println (log/println-appender {:stream :std-err})}}) + +(require '[ddc.client :as client]) + +(def record-schema-identifier + "http://clarin.eu/fcs/resource") + +(defn corpus->endpoint-config + [corpus] + (let [metadata (client/metadata corpus)] + [:endpoint-config + {:xmlns "http://www.clarin.eu/sru-server/1.0/"} + [:databaseInfo + [:title {:xml:lang "de"} (metadata :title-de)] + [:title {:xml:lang "en" :primary "true"} (metadata :title-en)] + [:description {:xml:lang "de"} (metadata :desc-de)] + [:description {:xml:lang "en" :primary "true"} (metadata :desc-en)] + [:author {:xml:lang "de"} (metadata :author-de)] + [:author {:xml:lang "en" :primary "true"} (metadata :author-en)]] + [:indexInfo + [:set {:name "fcs" :identifier "http://clarin.eu/fcs/resource"} + [:title {:xml:lang "en" :primary "true"} "CLARIN Content Search"]] + [:index {:search "true" :scan "false" :sort "false"} + [:title {:xml:lang "en" :primary "true"} "Words"] + [:map {:primary "true"} + [:name {:set "fcs"} "words"]]]] + [:schemaInfo + [:schema {:identifier record-schema-identifier + :name "fcs" + :sort "false" + :retrieve "true"} + [:title {:xml:lang "en" :primary "true"} "CLARIN Content Search"]]]])) + +(def capabilities + [(URI. "http://clarin.eu/fcs/capability/basic-search") + (URI. "http://clarin.eu/fcs/capability/advanced-search")]) + +(def all-data-views + [(DataView. "hits" "application/x-clarin-fcs-hits+xml" + DataView$DeliveryPolicy/SEND_BY_DEFAULT) + (DataView. "adv" "application/x-clarin-fcs-adv+xml" + DataView$DeliveryPolicy/SEND_BY_DEFAULT)]) + +(def data-layer->index + {"text" "w" + "lemma" "l" + "pos" "p" + "norm" "v" + "surface" "u"}) + +(def data-layer->uri + (into {} + (map #(vector % (URI. (str "http://dwds.de/ns/fcs/layer/" %)))) + (keys data-layer->index))) + +(defn data-layer + [id] + (Layer. id (data-layer->uri id) id Layer$ContentEncoding/EMPTY nil nil nil)) + +(def all-data-layers + (into [] (map data-layer) (keys data-layer->index))) + +(defn corpus->resource-info + [corpus] + (let [metadata (client/metadata corpus) + indices (client/indices corpus) + layers (into [] + (filter #(indices (data-layer->index (. % (getId))))) + all-data-layers)] + (ResourceInfo. + (metadata :pid) + {"de" (metadata :title-de) "en" (metadata :title-en)} + {"de" (metadata :desc-de) "en" (metadata :desc-en)} + nil + (metadata :url) ["deu"] + all-data-views layers nil))) + +(defn endpoint-desc + [corpus] + (SimpleEndpointDescription. + 2 + capabilities + all-data-views + all-data-layers + [(corpus->resource-info corpus)] + true)) + +(def default-num-records + 25) + +(def maximum-records + 250) + +(defn sru-server-config + [corpus] + (let [config (corpus->endpoint-config corpus) + config-f (fs/create-temp-file) + path (str env/http-context-path "/" corpus)] + (try + (with-open [output (io/output-stream (fs/file config-f))] + (->> config gx/sexp->node gx/node->events (gx/write-events output))) + (SRUServerConfig/parse + {SRUServerConfig/SRU_SUPPORTED_VERSION_MAX "2.0" + SRUServerConfig/SRU_TRANSPORT env/http-protocol + SRUServerConfig/SRU_HOST env/http-host + SRUServerConfig/SRU_PORT (str env/http-port) + SRUServerConfig/SRU_DATABASE path + SRUServerConfig/SRU_MAXIMUM_RECORDS (str maximum-records) + SRUServerConfig/SRU_ALLOW_OVERRIDE_MAXIMUM_RECORDS (str false) + SRUServerConfig/SRU_NUMBER_OF_RECORDS (str default-num-records)} + (.. config-f (toUri) (toURL))) + (finally + (fs/delete config-f))))) + +(defn assoc-space-after + [[t1 {ws "ws" :as _t2}]] + (assoc t1 "ws" (or ws "0"))) + +(defn parse-tokens + [indices tokens] + (let [tokens (map #(into {} (map vector indices %)) tokens)] + (into [] (map assoc-space-after) (partition-all 2 1 tokens)))) + +(defn result->writer + [result] + (let [indices (vec (cons "hl" (get-in result ["meta_" "indices_"]))) + tokens (parse-tokens indices (second (get result "ctx_"))) + writer (AdvancedDataViewWriter. AdvancedDataViewWriter$Unit/ITEM)] + (loop [n 1 offset 0 tokens tokens] + (when-let [{hl "hl" w "w" ws "ws" :as token} (first tokens)] + (let [ws? (not= ws "0") + end (+ offset (count w) (if ws? 1 0))] + (doseq [[layer index] data-layer->index + :let [v (token index)] :when v + :let [v (cond-> v (and (= index "w") ws?) (str " "))]] + (. writer addSpan (data-layer->uri layer) (inc offset) end v hl)) + (recur (inc n) end (rest tokens))))) + writer)) + +(defn result-link + [corpus query] + (-> (uri/uri "https://www.dwds.de/r/") + (uri/assoc-query :corpus corpus :q query) + (str))) + +(defn search + [corpus request diagnostics] + (let [endpoint (client/endpoints corpus) + metadata (client/metadata corpus) + pid (metadata :pid) + query (query/->ddc (. request (getQuery))) + frag-ref (result-link corpus query) + query (str query " !#has[avail,OR0W] #separate") + start-record (. request (getStartRecord)) + num-records (min (. request (getMaximumRecords)) maximum-records) + results (into [] + (take num-records) + (client/query endpoint query + :offset (dec start-record) + :page-size (min num-records 1000))) + total (or (some-> results first meta :total) 0) + num-results (count results) + result-idx (volatile! 0)] + (proxy [SRUSearchResultSet] [diagnostics] + (getTotalRecordCount [] (min maximum-records total)) + (getRecordCount [] (count results)) + (getResultCountPrecision [] SRUResultCountPrecision/EXACT) + (getRecordSchemaIdentifier [] record-schema-identifier) + (nextRecord [] (< @result-idx num-results)) + (getRecordIdentifier [] nil) + (writeRecord [writer] + (let [result (results @result-idx) + data-writer (result->writer result)] + (XMLStreamWriterHelper/writeStartResource writer pid nil) + (XMLStreamWriterHelper/writeStartResourceFragment writer nil frag-ref) + (. data-writer (writeHitsDataView writer (data-layer->uri "text"))) + (. data-writer (writeAdvancedDataView writer)) + (XMLStreamWriterHelper/writeEndResourceFragment writer) + (XMLStreamWriterHelper/writeEndResource writer) + (vswap! result-idx inc) + nil)) + (hasExtraRecordData [] false) + (writeExtraRecordData [writer])))) + +(defn throwable->diagnostic + [t] + (when-let [uri (some-> t ex-data :sru-diagnostic-uri)] + (let [message (. t (getMessage)) + details (some-> t ex-data :sru-diagnostic-details)] + (SRUException. uri details message t)))) + +(defn search-engine + [corpus] + (let [endpoint-desc (endpoint-desc corpus)] + (proxy [SimpleEndpointSearchEngineBase] [] + (doInit [_context _config _query-parsers _params]) + (createEndpointDescription [_context _config _params] endpoint-desc) + (search [_config request diagnostics] + (try + (search corpus request diagnostics) + (catch Throwable t + (throw (or (throwable->diagnostic t) + (SRUException. + SRUConstants/SRU_GENERAL_SYSTEM_ERROR + (. t (getMessage)) + t))))))))) + +(defn sru-servlet + [corpus] + (let [server-config (sru-server-config corpus) + query-parsers (SRUQueryParserRegistry$Builder.) + engine-params {} + engine (search-engine corpus)] + (. engine (init nil server-config query-parsers engine-params)) + (let [server (SRUServer. server-config (.. query-parsers (build)) nil engine)] + (proxy [HttpServlet] [] + (doGet [req resp] (. server (handleRequest req resp))) + (doPost [req resp] (. server (handleRequest req resp))))))) + +(defn stop! + [^Server server] + (log/infof "Stopping HTTP service %s" server) + (.stop server) + (.join server)) + +(defn start! + [] + (log/infof "Starting HTTP service @ %d/tcp" env/http-server-port) + (let [server (Server.) + connector (ServerConnector. server) + servlets (ServletContextHandler.)] + (. connector (setPort env/http-server-port)) + (. servlets (setContextPath env/http-context-path)) + (doseq [corpus (keys client/corpora) :let [servlet (sru-servlet corpus)]] + (. servlets (addServlet (ServletHolder. servlet) (str "/" corpus)))) + (. server (addConnector connector)) + (. server (setHandler servlets)) + (. server (start)) + (partial stop! server))) + +(defn serve + [& _] + (let [stop! (start!)] + (.. (Runtime/getRuntime) (addShutdownHook (Thread. stop!))) + @(promise))) diff --git a/src/ddc/query.clj b/src/ddc/query.clj new file mode 100644 index 0000000..f593a6f --- /dev/null +++ b/src/ddc/query.clj @@ -0,0 +1,237 @@ +(ns ddc.query + (:require + [clojure.string :as str]) + (:import + (eu.clarin.sru.server CQLQueryParser$CQLQuery SearchTermsQueryParser$SearchTermsQuery SRUConstants) + (eu.clarin.sru.server.fcs Constants FCSQueryParser$FCSQuery) + (eu.clarin.sru.server.fcs.parser Expression ExpressionAnd ExpressionGroup ExpressionNot ExpressionOr ExpressionWildcard Operator QueryDisjunction QueryGroup QueryNode QuerySegment QuerySequence QueryWithWithin RegexFlag SimpleWithin SimpleWithin$Scope) + (org.z3950.zing.cql CQLAndNode CQLNode CQLNotNode CQLOrNode CQLProxNode CQLRelation CQLTermNode))) + +(defn sru-diagnostic + [uri message details] + (ex-info message {:sru-diagnostic-uri uri + :sru-diagnostic-details details})) + +(defn fcs-query-unsupported + [details] + (sru-diagnostic + Constants/FCS_DIAGNOSTIC_GENERAL_QUERY_TOO_COMPLEX_CANNOT_PERFORM_QUERY + "Query too complex/ cannot perform query" + details)) + +(defn ddc-escape-term + "DDC terms/phrase are single/double-quoted, so we need to escape quotes." + [s] + (-> s + (str/replace #"\\" "\\\\\\\\") + (str/replace #"['\"]" "\\\\$0"))) + +(letfn [(cql-modifier [type modifiers] + (when-let [modifier (first (filter #(= type (. % (getType))) modifiers))] + (list (. modifier (getComparison)) (. modifier (getValue)))))] + (defn cql-modifiers->distance + [modifiers] + (let [[ucmp uval] (cql-modifier "unit" modifiers) + [dcmp dval] (cql-modifier "distance" modifiers) + unit-valid? (or (and (nil? ucmp) (nil? uval)) + (and (#{"=" "=="} ucmp) + (#{"any" "word" "token"} uval))) + distance-valid? (or + (and (nil? dcmp) (nil? dval)) + (and (#{"=" "=="} dcmp) (= "0" dval)) + (and (#{"<" "<="} dcmp) (re-seq #"[0-9]+" dval))) + distance (if (and distance-valid? dval) (parse-long dval) 0)] + (when-not distance-valid? + (throw (ex-info "prox/distance invalid" {:cmp dcmp :value dval}))) + (when-not unit-valid? + (throw (ex-info "prox/unit invalid" {:cmp ucmp :value uval}))) + (if (and (< 0 distance) (= "<" dcmp)) (dec distance) distance)))) + +(defprotocol Translation + (->ddc [this])) + +(extend-protocol Translation + + SearchTermsQueryParser$SearchTermsQuery + (->ddc [query] + (let [terms (. query (getParsedQuery))] + (str/join " && " (map (comp #(str "'" % "'") ddc-escape-term) terms)))) + + CQLQueryParser$CQLQuery + (->ddc [query] (->ddc (. query (getParsedQuery)))) + + FCSQueryParser$FCSQuery + (->ddc [query] (->ddc (. query (getParsedQuery)))) + + CQLRelation + (->ddc [rel] + (condp = (. rel (getBase)) + "==" "@" + "exact" "@" + "=" "" + "scr" "" + (throw (sru-diagnostic SRUConstants/SRU_UNSUPPORTED_RELATION + "Unsupported relation" + (str rel))))) + + CQLTermNode + (->ddc [node] + (let [index (. node (getIndex))] + (when-not (#{"cql.serverChoice" "fcs.words" "words"} index) + (throw (sru-diagnostic + SRUConstants/SRU_UNSUPPORTED_INDEX + "Unsupported index" + (str index))))) + (let [relation (->ddc (. node (getRelation))) + terms (str/split (. node (getTerm)) #"\s+") + terms (map (comp #(str relation "'" % "'") ddc-escape-term) terms) + phrase (if (second terms) + (str "\"" (str/join " " terms) "\"") + (first terms))] + phrase)) + + CQLAndNode + (->ddc [node] + (format "( %s && %s)" + (->ddc (. node (getLeftOperand))) + (->ddc (. node (getRightOperand))))) + + CQLOrNode + (->ddc [node] + (format "( %s || %s)" + (->ddc (. node (getLeftOperand))) + (->ddc (. node (getRightOperand))))) + + CQLNotNode + (->ddc [node] + (format "( %s && !%s)" + (->ddc (. node (getLeftOperand))) + (->ddc (. node (getRightOperand))))) + + CQLProxNode + (->ddc [node] + (format "NEAR(%s, %s, %s)" + (->ddc (. node (getLeftOperand))) + (->ddc (. node (getRightOperand))) + (cql-modifiers->distance (.. node (getModifiers))))) + + CQLNode + (->ddc [node] + (throw (sru-diagnostic SRUConstants/SRU_QUERY_FEATURE_UNSUPPORTED + "Query feature unsupported" + (str node)))) + + Expression + (->ddc [node] + (let [qualifier (or (. node (getLayerQualifier)) "") + identifier (. node (getLayerIdentifier)) + [field expan] (cond + (#{"word" "token"} identifier) ["$w"] + (#{"norm" "orth"} identifier) ["$v"] + (#{"surface"} identifier) ["$u"] + (#{"lemma"} identifier) ["$l"] + ;; (un-)qualified text attribute, e.g. `text`, `word.text` + (#{"text"} identifier) + (cond + (#{"surface" "utf8"} qualifier) ["$u"] + (#{"word" "latin1" ""} qualifier) ["$w"] + (#{"norm" "orth" "canonical"} qualifier) ["$v"]) + ;; (un-)qualified POS attribute, e.g. `pos`, `stts.pos` + (#{"pos"} identifier) + (cond + (#{"stts"} qualifier) ["$p"] + (#{"ud" ""} qualifier) ["$p" "pos-ud"])) + pattern (. node (getRegexValue)) + regex-flags (into #{} (. node (getRegexFlags))) + literal? (and (empty? regex-flags) + (re-matches #"^[^^$\\.?*+{}()\[\]|]*$" pattern))] + (when (and expan (not literal?)) + (throw (fcs-query-unsupported "DDC-expanded regex"))) + (format + (condp = (. node (getOperator)) + Operator/EQUALS "%s=%s%s" + Operator/NOT_EQUALS "!%s=%s%s") + field + (if literal? + (str "'" (ddc-escape-term pattern) "'") + (let [flags (cond-> "g" + (regex-flags RegexFlag/IGNORE_DIACRITICS) (str "d") + (regex-flags RegexFlag/CASE_INSENSITIVE) (str "i"))] + (as-> pattern $ + (cond->> $ + (regex-flags RegexFlag/LITERAL_MATCHING) (format "\\Q%s\\E")) + (str/replace $ #"/" "\\\\/") + (str/replace $ #"\\u([0-9A-Fa-f]{1,4})" "\\\\x{$1}") + (str/replace $ #"\\U([0-9A-Fa-f]{1,8})" "\\\\x{$1}") + (str "/" $ "/" flags)))) + (cond-> "" expan (str "|" expan))))) + + ExpressionAnd + (->ddc [node] + (str "(" (str/join " &= " (map ->ddc (. node (getChildren)))) ")")) + + ExpressionOr + (->ddc [node] + (str "(" (str/join " |= " (map ->ddc (. node (getChildren)))) ")")) + + ExpressionNot + (->ddc [_node] + (throw (fcs-query-unsupported "Negation not supported"))) + + ExpressionGroup + (->ddc [_node] + (throw (fcs-query-unsupported "Group queries not supported"))) + + ExpressionWildcard + (->ddc [_node] "*") + + QueryDisjunction + (->ddc [node] + (str/join " || " (map ->ddc (. node (getChildren))))) + + QueryGroup + (->ddc [_node] + (throw (fcs-query-unsupported "Grouped/quantified queries not supported"))) + + QuerySegment + (->ddc [node] + (let [expression (. node (getExpression)) + min-occurs (min 32 (max 0 (. node (getMinOccurs)))) + max-occurs (min 32 (. node (getMaxOccurs))) + max-occurs (if (= QueryNode/OCCURS_UNBOUNDED max-occurs) 32 max-occurs)] + (cond + ;; not quantified + (and (= 1 min-occurs) (= 1 max-occurs)) + (->ddc expression) + ;; quantified wildcard + (instance? ExpressionWildcard expression) + (->> + (cond->> (repeat min-occurs "*") + (< min-occurs max-occurs) + (concat (list (str "#" (- max-occurs min-occurs))))) + (str/join " " )) + ;; unsupported + :else + (throw (fcs-query-unsupported + "Quantifiers only supported for wildcard segments"))))) + + QuerySequence + (->ddc [node] + (str "\"" (str/join " " (map ->ddc (. node (getChildren)))) "\"")) + + QueryWithWithin + (->ddc [node] + (let [scope (. node (getWithin))] + (when-not (instance? SimpleWithin scope) + (throw (fcs-query-unsupported "Only simple query scopes supported"))) + (str (->ddc (. node (getQuery))) " WITHIN " (->ddc scope)))) + + SimpleWithin + (->ddc [node] + (condp = (. node (getScope)) + SimpleWithin$Scope/PARAGRAPH "p" + SimpleWithin$Scope/SENTENCE "s" + SimpleWithin$Scope/SESSION "file" + SimpleWithin$Scope/TEXT "file" + SimpleWithin$Scope/TURN "file" + SimpleWithin$Scope/UTTERANCE "u"))) diff --git a/test/ddc/query_test.clj b/test/ddc/query_test.clj new file mode 100644 index 0000000..1622efa --- /dev/null +++ b/test/ddc/query_test.clj @@ -0,0 +1,89 @@ +(ns ddc.query-test + (:require [ddc.query :as query] + [clojure.test :refer [deftest is testing]]) + (:import (org.z3950.zing.cql CQLParser) + (eu.clarin.sru.server.fcs.parser QueryParser))) + +(defn parse-cql + [s] + (let [parser (CQLParser. CQLParser/V1POINT2)] + (. parser (parse s)))) + +(defn cql-parses + [cql-q] + (is (some? (parse-cql cql-q)))) + +(defn cql->ddc + [cql-q] + (-> cql-q parse-cql query/->ddc)) + +(defn cql-is-ddc? + [cql-q ddc-q] + (is (= ddc-q (cql->ddc cql-q)))) + +(defn cql->ddc-fails? + [cql-q] + (is (thrown? Exception (-> cql-q parse-cql query/->ddc)))) + +(deftest cql-parsing + (testing "CQL parsing and DDC conversion" + (testing "Grammar" + (cql-parses "fish") + (cql-parses "dc.title any test") + (cql-parses "dc.title any fish or dc.creator any sanderson") + (cql-parses "dc.title any fish sortBy dc.date/sort.ascending") + (cql-parses "cql.serverChoice = fish") + (cql-parses "dc.title cql.any fish") + (cql-parses "dc.title any/rel.algorithm=cori fish") + (cql-parses + "> dc = \"info:srw/context-sets/1/dc-v1.1\" dc.title any fish") + (cql-parses + "dc.title any fish or (dc.creator any yi and dc.identifier = \"id:123\")") + (cql-parses + "dc.title any fish or/rel.combine=sum dc.creator any sanderson") + (cql-parses + "dc.title any fish prox/unit=word/distance>3 dc.title any squirrel")) + (testing "Expressions" + (cql-is-ddc? "testen" "'testen'") + (cql-is-ddc? "\"er hat\"" "\"'er' 'hat'\"") + (cql-is-ddc? "er prox/distance<3/unit=word hat" "NEAR('er', 'hat', 2)") + (cql->ddc-fails? "text == testen")))) + +(defn parse-fcs + [fcs-q] + (. (QueryParser.) (parse fcs-q))) + +(defn fcs-parses + [fcs-q] + (is (some? (parse-fcs fcs-q)))) + +(defn fcs->ddc + [fcs-q] + (-> fcs-q parse-fcs query/->ddc)) + +(defn fcs-is-ddc? + [fcs-q ddc-q] + (is (= ddc-q (fcs->ddc fcs-q)))) + +(deftest fcs-ql-parsing + (testing "FCS-QL parsing and DDC conversion" + (testing "Grammar" + (fcs-parses "\"walking\"") + (fcs-parses "[token = \"walking\"]") + (fcs-parses "\"Dog\" /c") + (fcs-parses "[pos = \"NOUN\"]") + (fcs-parses "[pos != \"NOUN\"]") + (fcs-parses "[lemma = \"walk\"]") + (fcs-parses "\"blaue|grüne\" [pos = \"NOUN\"]") + (fcs-parses "\"dogs\" []{3,} \"cats\" within s") + (fcs-parses "[z:pos = \"ADJ\"]") + (fcs-parses "[z:pos = \"ADJ\" & q:pos = \"ADJ\"]") + (fcs-parses "[pos = 'ADJ']{1,2} [text = 'query'] | 'term' within s") + (fcs-parses "[pos = 'ADJ']{1,2} [] 'testen' within s")) + (testing "Expressions" + (fcs-is-ddc? "[pos=\"NN\"]" + "$p='NN'|pos-ud") + (fcs-is-ddc? "[lemma=\"test\"]" + "$l='test'") + (fcs-is-ddc? "[word=\"lopen\"] [word =\"op\" & pos=\"ADP\"]" + "\"$w='lopen' ($w='op' &= $p='ADP'|pos-ud)\"")))) diff --git a/tests.edn b/tests.edn new file mode 100644 index 0000000..82c0557 --- /dev/null +++ b/tests.edn @@ -0,0 +1,7 @@ +{:kaocha/tests [{:kaocha.testable/type :kaocha.type/clojure.test + :kaocha.testable/id :unit + :kaocha/ns-patterns ["-test$"] + :kaocha/source-paths ["src"] + :kaocha/test-paths ["test"]}] + :kaocha/color? true + :kaocha/reporter [kaocha.report/documentation]}